Can't seem to get headers to work. Using Visual C++ 2008

I'm trying to write a basic program using class/function header files and can't seem to get this to work/link together.

It might just be the order that I'm doing my #includes and such in, but the two errors that I'm getting right now are:

: error C2871: 'std' : a namespace with this name does not exist
: error C2065: 'cout' : undeclared identifier

This is what my code looks like:
main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "header.h"

int main(){

        Stuff myStuff;
        myStuff.setData( 5 );
        myStuff.printData();
        return 0;

}

header.h
1
2
3
4
5
6
7
8
9
10
#pragma once
#define HEADER_H
using namespace std;

class Stuff{
        int data;
        public:
                void setData(int);
				void printData() {cout << data;}
};

header.cpp
1
2
3
4
5
#include "header.h"

void Stuff::setData (int x){
        data = x;
}


Even more odd to me was that when I wrote the same program on my school's linux server and compiled with g++, I got a different looking error:

$ g++ main.cpp
/tmp/cca5fvnX.o: In function `main':
main.cpp:(.text+0x19): undefined reference to `Stuff::setData(int)'
collect2: ld returned 1 exit status


I google'd around a bit and didn't find the answer to my problem. I've been kind of trying to teach myself how to do C++ with what I read online, have I read something wrong?
error C2871: 'std' : a namespace with this name does not exist
: error C2065: 'cout' : undeclared identifier


Thats because the namespace std is defined in the header file <iostream>. So you must include it(<iostream>) in the header file you want to use this namespace.

HTH,
Aceix.
Thanks for the reply!

I tried to #include <iostream> above >using namespace std; but that generated a linking error.

After I read a bit more, I learned that it might not necessarily be a good programming practice to use "using", and I understand why. I might just prefix all of my iostream functions with std::
#1 you don't have to include <iostream> in header.h, but it does make it easier to handle. What you need to do is ensure <iostream> is included before it's used, so you could have altered header.cpp to

1
2
3
4
5
6
#include <iostream>
#include "header.h"

void Stuff::setData (int x){
        data = x;
}


#2 note it is seen as bad practice to use a using directive in a header. Ideally you move it to just after the includes in the .cpp file

This would mean you would either have had to add std:: before cout in your header, or split the method implementation out into the .cpp file.

#3 the g++ error suggests you are only building main.cpp, so the linker cannot find header.cpp

Did you try

$ g++ main.cpp header.cpp
Last edited on
Topic archived. No new replies allowed.