Alfred Hobson
Alfred Hobson

Reputation: 21

global vector C++

Is it possible to have a vector as a global variable is C++? Like this:

class system {...};
vector<system> systems;

when I try to compile this I get an error. The compiler I'm using is gcc and I'm compiling as C++.

Upvotes: 2

Views: 3498

Answers (6)

Macke
Macke

Reputation: 25680

system() is a c-stdlib function, hence possibly an already defined name, so you can't re-use it.

Re-name it to something else (System?) and post the full error message next time, plz.

Upvotes: 6

PierreBdR
PierreBdR

Reputation: 43264

The error is, as often, in windows.h ! "system" is defined in "windows.h" or something included in it. I suppose it's the function to make a system call.

Upvotes: 0

Trent
Trent

Reputation: 13477

When I compile your code with g++ 3.4.4 under Cygwin I get the following errors:

test.cpp:8: error: type/value mismatch at argument 1 in template parameter list for `template class std::vector'

test.cpp:8: error: expected a type, got `system'

test.cpp:8: error: template argument 2 is invalid

test.cpp:8: error: invalid type in declaration before ';' token

The problem is your class name system, either change the name of the class or use:

vector<class system> systems

Upvotes: 3

Nemanja Trifunovic
Nemanja Trifunovic

Reputation: 24561

I bet you declared it in a header file without extern

Upvotes: 1

VDVLeon
VDVLeon

Reputation: 1394

Yes that can like this:

#include <vector>

class system{ ... };

std::vector<system> systems;

So the vector global var is defined after the definition of the class system. Vector must be included and don't forget std:: before vector (or using namespace std).

Edit: I just thought of something. There is also a function called system. Try a different class name.

Upvotes: 7

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

Do you mean this:

#include<iostream>
#include<vector>
using namespace std;
class system{
  // class members
 };

vector<system> v;

int main()
{
   //do something
}

It works fine in my g++ compiler. I don't think there should be any problem defining a vector variable globally, but it is not recommended.

Upvotes: 0

Related Questions