`does not name a type` error with `namespace std;` and files
Solution 1
Yes but in this example functions.cpp
has not seen using namespace std
since you only wrote that in main.cpp
.
Don't add using namespace std
to functions.h
, use std::
to qualify types. Adding a using..
imposes an unnecessary burden on the user of your header.
Solution 2
You need to qualify the namespace:
#include "functions.h"
std::vector<int> x;
You have a using namespace std
in main.cpp
, and it cannot be seen by functions.cpp
. That is the root of the problem.
In general, you should avoid using namespace std
, specially in headers. And if you really must include it in main
, put it after all the headers.
Solution 3
You imported the std
namespace only in main.cpp
, not in functions.cpp
.
You have to qualify your use - std::vector
in the second file, or use the using
directive:
//functions.cpp
#include "functions.h"
std::vector <int> x; // preferred
or
//functions.cpp
#include "functions.h"
using namespace std;
vector <int> x;
or (bonus)
//functions.cpp
#include "functions.h"
using std::vector;
vector <int> x;
Declaring namespace at the top of main.cpp usually works across all .cpp files for me.
You have a really flawed compiler then. using
directives shouldn't influence translation units that don't have direct visibility over the directive.
Solution 4
You using namespace std
is local to main.cpp only. You need to use
std::vector<int> x;
in your source file functions.cpp
Related videos on Youtube
Comments
-
Matt Munson over 3 years
compiling the code below with
g++ main.cpp functions.cpp -o run
gives me the errorerror: ‘vector’ does not name a type
. Declaring namespace at the top ofmain.cpp
usually works across all.cpp
files for me.main.cpp
using namespace std; #include "functions.h" main () {}
functions.h
#include <vector>
functions.cpp
#include "functions.h" vector <int> x;
EDIT: I appreciate the fact all responders know what their talking about, but this normally works for me. Would the use of a makefile have any bearing on that? something else that I might be missing?
-
Matt Munson over 11 yearsI will change downvote to an upvote for anyone who adresses the fact that this usually works for me. Even your answers is only speculative.
-
juanchopanza over 11 years@MattMunson it cannot possibly work for you (in this particular case), because
using namespace std
is not seen infunctions.cpp
. And assuming thatusing namespace std
can be seen somewhere can only lead to trouble.