我想了解如何在C++中包含多個文件。我做了很多搜索,最後我寫了一個測試代碼,總結了我的問題。我有兩個頭文件和兩個cpp文件看起來像這樣:即使在包含頭文件之後,程序仍會給出LNK2019錯誤
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();
}
我的主文件看起來如下:
TEST.CPP:
#include <iostream>
#include "test2.h"
#include "test1.h"
int main()
{
func1();
func2();
getchar();
return 0;
}
我使用VS10,我只補充說: 「TEST.CPP」 作爲源文件。當我編譯此代碼我收到以下錯誤:
**1>test.obj : error LNK2019: unresolved external symbol "void __cdecl func2(void)" ([email protected]@YAXXZ) referenced in function _main **
**1>test.obj : error LNK2019: unresolved external symbol "void __cdecl func1(void)" ([email protected]@YAXXZ) referenced in function _main **
我不太瞭解,甚至包括兩個頭文件,爲什麼我會收到此之後?我錯過了什麼?
任何幫助,將不勝感激!
感謝 新手
謝謝Hertzel ...包括test1.cpp和test2.cpp解決了這個問題。現在有點顯而易見了,但我之前認爲只包括頭文件應該考慮到這一點。 – Richeek 2011-03-26 20:08:10
你是對的「val」。但是,如果我這樣做:static const int val = 10;如果我想聲明一個全局const變量。有用。那這是一個好習慣嗎? – Richeek 2011-03-26 20:08:43
@Newbie:比較好。 – 2011-03-26 20:26:49