简体   繁体   中英

How to use header files?

I wanted to learn using header files. and I got an error. here is my code:

printmyname.h:

void printMyName();

printmyname.cpp:

#include "printmyname.h"

void printMyName() {
    cout << "omer";
}

try.cpp (main file):

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


int main() {
    printMyName();

    return 0;
}

Here is the error:

undefined reference to `printMyName()`

What's is the problem?

Undefine reference has nothing to do with your header file in this case. It means the linker cannot find the implementation of printMyName which is in printmyname.cpp . If you are using g++ , you should try:

g++ try.cpp printmyname.cpp -o yourBinaryName

If you are using a makefile, you should add dependency(printmyname.cpp) correctly for try.cpp.

Edit:

As @zmo suggest in his comment:

you can also do it through a two times compilation (more suitable with Makefiles):

g++ -c printmyname.cpp 
g++ try.cpp printmyname.o -o yourBinaryName

If you are using Windows, you need to add the printmyname.cpp to your project too. Consider adding an include guard to your header

#ifndef PRINTMYNAME_INCLUDED 
#define PRINTMYNAME_INCLUDED 

void printMyName();

#endif

You will also need to move the #include <iostream> and using namespace std; from the try.cpp to the printmyname.cpp file.

You need to add code/definition in printMyName.cpp inside printMyName.h only.

void printMyName();
{
    cout << "omer";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM