Program gives LNK2019 error even after including header files
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 *开发者_StackOverflow*
**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 = 10
on the header file is wrong - you'll have linkage problem.
Put it in a cpp file and use extern int val
on its header.
HTH
You will have to tell the compiler to compile all the cpp files. The compiler builds object files with the cpp files, such as test1.obj, test2.obj, and test.obj. Then, it links these objects together into a library or an executable.
What you are getting is a linker error saying, ok, test.obj uses func1 and func2, and I have the declaration of these funcs in test1.h and test2.h, but where are they implemented? I don't have test1.obj nor test2.obj, compiler seems not to have built them.
Including header files rarely solves link errors. Usually, headers give you function declarations. You then need to link the libraries that give you the function definitions.
In this case, you say that you only have test.cpp
in your project. This means that test1.cpp
and test2.cpp
are neither compiled nor linked, and consequently the function definitions don't exist.
Add test1.cpp
and test2.cpp
to your VS project.
精彩评论