A very simple header file

I've been trying to learn how to use header files because they seem incredibly useful. I am having difficulties with getting even a simple header file to work though.

This would be a basic example that I would expect to have output from the code below.


1
2
Hello World
2


What am I doing wrong?

Main.cpp

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
#include "myheader.h" // my header file

int main()
{

    std::cout << print_message("Hello World") << "\n";
    return 0;
}


myheader.h

1
2
3
4
5
6
7
#ifndef myheader.h
#define myheader.h
#include <string>

int print_message(std::string a);

#endif 



print_message.cpp

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

int print_message (std::string a){
    std::cout << a << "\n";
    return 2;
}

Last edited on
In myheader.h, you should probably #include <string> (doesn't matter if you put it before or after the include guard, though I typically prefer to put it after).
That way, you won't get an error if you #include "myheader.h" before you #include <string> .

That being said, you're probably not linking the files right.
If you use an IDE, try making a project with those three files and then compiling it.
If you compile via the command line, you'd have to do something like this (this is for GCC; if you use a different compiler, you'll have to look it up yourself):
1) Compile your files (but don't link):
g++ -c print_message.cpp
g++ -c Main.cpp

(and stick whatever compiler options you usually use in there)
2) Link:
g++ Main.o print_message.o -o my_output_filename.exe

Ok i changed it the way you are suggesting. Now the only error I'm getting is this in the print_message.cpp


error: 'cout' is not a member of std


I am using an IDE called Code::Blocks and the GCC compiler.

It is very possible I am not compiling correctly if there is nothing wrong with the code above. I will have to read about this.
Last edited on
Whoops, sorry, I forgot to tell you that you'll also need to #include <iostream> in print_message.cpp. (Doesn't matter if it's before or after the other #include .)

That's because it's a separate .cpp file, so the compiler can't "see" the <iostream> from your Main.cpp file.
thanks you!! it works now :)

I messed around and it seems I can put all of the #Include 's into the header file and just include myheader.h in each other file.

Is that an ok practice to get into or is it preferred to have only the Includes needed in each file.

Not entirely sure what is best. I mean if i put all the includes in the header some files might get includes they don't need but it seems easier to put them all in header file.
Last edited on
Topic archived. No new replies allowed.