neo1691
neo1691

Reputation: 131

Confusion between including header files and source files in main program

I have heard that we should write the declarations in a header file and the definition in a source file, with both the source and the header having the same name. And then just include the header in the source.

Here is an example myFile.h:

void printer (void);

Here is the implementation of printer in myFile.cpp:

#include "myFile.h"
#include <iostream>
using namespace std;

void printer ()
{
    cout<< "I am a printer";
}

Here is my main.cpp:

#include "myFile.h"

int main ()
{
    printer();
    return 0;
}

Now when I run the program, I get the expected error: undefined reference to printer. But when I see code on github or other projects I see that usually they have included the header file and not the source file. I also tried using the header guards ifndef but still the same error came. The main program is successfully compiled if:

  1. If i include myFIle.cpp in myFile.h

  2. If i include just myFile.cpp in main

What I the general practice while doing the same?

Upvotes: 1

Views: 1510

Answers (4)

Zeta
Zeta

Reputation: 105876

You should include your myFile.cpp in the linking process:

g++ myFile.cpp main.cpp

The error message undefined reference to printer is actual a linker error, not a compiler error.

Explanation

If you use only g++ main.cpp compiler won't create code from myFile.cpp. He knows that there should be a function with the signature void printer(void), but he doesn't now yet where this function is. He completely ignores this fact, since you can provide pre-compiled object files ("myFile.o") and link those later:

g++ myFile.cpp -c       # compile myFile.cpp
g++ main.cpp -c         # compile myFile.cpp
g++ myFile.o main.o     # link both files together.

-c will tell g++ only to compile the files, but not link them together to an executable. This is done by a linker (g++ will probably call ld in your configuration). The linker will create an executable which contains all needed libraries like libc++ and actual code.

IDE remarks

If you use an IDE make sure that all needed files are included in the project. This includes all header and source files and linkage options for additional libraries.

Upvotes: 4

stefan bachert
stefan bachert

Reputation: 9608

You should use

#include "myFile.h"

or

#include <myFile.h>

the later is rather for system libraries. Both forms differ in the way the search the file. You find more details on

http://msdn.microsoft.com/en-us/library/36k2cdd4%28v=vs.71%29.aspx

Upvotes: 0

Benny
Benny

Reputation: 4321

#include "myFile.h" // would be better.

It seems you forgot the " surrounding the include.

Upvotes: 1

PersianGulf
PersianGulf

Reputation: 2935

When yourself define a header file and want to include it, you should enclose it "", such as :

#include "myFile.h"

Upvotes: 1

Related Questions