I am trying to understand how including multiple files in C++ works. I did a lot of searching and finally I wrote a test code which is summarizes my problem. I have two header files and two cpp files that look like this:
test1.h:
#ifndef _TEST_1_H
#define _TEST_1_H
int val = 10;
void func1();
#endif
test2.h:
#ifndef _TEST_2_H
#define _TEST_2_H
#include "test1.h"
void func2();
#endif
test1.cpp:
#include <iostream>
#include "test1.h"
void func1()
{
std::cout<<val<<std::endl;
}
test2.cpp:
#include <iostream>
#include "test2.h"
void func2()
{
func1();
}
And my main file looks as follows:
test.cpp:
#include <iostream>
#include "test2.h"
#include "test1.h"
int main()
{
func1();
func2();
getchar();
return 0;
}
I am using VS10 and I have only added “test.cpp” as source file. When I compile this code I get following error:
**1>test.obj : error LNK2019: unresolved external symbol "void __cdecl func2(void)" (?func2@@YAXXZ) referenced in function _main **
**1>test.obj : error LNK2019: unresolved external symbol "void __cdecl func1(void)" (?func1@@YAXXZ) referenced in function _main **
I don’t quite understand even after including both the header files why am I getting this? What am I missing?
Any help would be appreciated!
Thanks
Newbie
Including the files only satisfy the compiler. You need to link all of the obj files together.
If you are using visual studio, make sure all of those files are included in the project you’re building.
One a side note, using
int val = 10on the header file is wrong – you’ll have linkage problem.Put it in a cpp file and use
extern int valon its header.HTH