Help with vectors with multiple CPP files

I've just stepped into the realm of using multiple files; so far, all has gone well...until...
I'm having a boatload of trouble trying to figure out a solid way to "spread" a vector across multiple .cpp files.
A simplified example of what I'm trying to do:
main cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
#include "Header.h"

using namespace std;

vector<int>vec(10);
int main()
{
	setit(&vec);
	return 0;
}
  

Header.h:
1
2
3
4
5
6
7
#ifndef HEADER_H
#define HEADER_H

extern std::vector<int>vec;
void setit(vector<int>*temp);

#endif 

func.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
#include "Header.h"

using namespace std;

void setit(vector<int>*temp)
{
	for (int n{}; n < 10; n++)
	{
		temp->push_back(n * 20);
	}
}

Basically, I need to be able to pass vec to the "setit" function as a pointer.
In a single file, this would work like a charm, but I haven't been able to get this to work. Multiple compiler errors.
For whatever reason, in header.h the lone definition
 
extern std::vector<int>vec;

works fine, until I put the header in header.h, which is when intellisense starts complaining.
So, all being said, what exactly is the "proper" way to make a vector available across multiple .cpp files?
Any help would be most appreciated.
Cheers!
You don't want to "spread".
You don't want global variables.
You should not want pointers.

Use reference parameters:
1
2
3
4
5
6
7
8
9
#include <vector>
#include "Header.h"

int main()
{
  std::vector<int> vec(10);
  setit( vec );
  return 0;
}


1
2
3
4
5
6
7
#ifndef HEADER_H
#define HEADER_H
#include <vector>

void setit( std::vector<int> & temp );

#endif  


1
2
3
4
5
6
7
8
9
10
#include <vector>
#include "Header.h"

void setit( std::vector<int> & temp )
{
  for ( int n = 0; n < ????; ++n )
  {
    temp[n] = n * 20;
  }
}
Last edited on
Topic archived. No new replies allowed.