2011-04-21 96 views
0

我想在linux中编译一个简单的应用程序。我的main.cpp看起来像在Linux中编译C++

#include <string> 
#include <iostream> 
#include "Database.h" 

using namespace std; 
int main() 
{ 
    Database * db = new Database(); 
    commandLineInterface(*db); 
    return 0; 
} 

其中Database.h是我的头并有一个相应的Database.cpp。编译时出现以下错误:

[email protected]:~/code$ g++ -std=c++0x main.cpp -o test 
/tmp/ccf1PF28.o: In function `commandLineInterface(Database&)': 
main.cpp:(.text+0x187): undefined reference to `Database::transducer(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
main.cpp:(.text+0x492): undefined reference to `Database::transducer(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
main.cpp:(.text+0x50c): undefined reference to `Database::transducer(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)' 
/tmp/ccf1PF28.o: In function `main': 
main.cpp:(.text+0x721): undefined reference to `Database::Database()' 
collect2: ld returned 1 exit status 

搜索类似这样的东西遍布整个地方,你可以想象得到。对于我可以做些什么来解决问题有什么建议?

+1

我想我们需要看看Database。(h | cpp)文件,或者至少是'Database'类和'commandLineInterface'接口/实现。 – 2011-04-21 15:05:21

回答

5

那些是链接器错误。它抱怨,因为它试图产生最终的可执行文件,但它不能,因为它没有用于Database函数的目标代码(编译器不推断对应于Database.h的函数定义存在于Database.cpp中)。

试试这个:

g++ -std=c++0x main.cpp Database.cpp -o test 

或者:

g++ -std=c++0x main.cpp -c -o main.o 
g++ -std=c++0x Database.cpp -c -o Database.o 
g++ Database.o main.o -o test 
+0

我怀疑这一点,但不确定。现在我的数据库类有其他包含等等。当然有一种方法可以编译所有内容,而无需每次都输入它?脚本还是有g ++选项? – Pete 2011-04-21 15:16:34

+1

@Pete - 你想要一个make文件。 http://www.gnu.org/software/make/manual/make.html或者使用将为您的项目创建一个的IDE。 – Duck 2011-04-21 16:31:40

2

您参考Database.h中的代码,因此您必须在库或通过目标文件Database.o(或源文件Database.cpp)中提供实现。

0

而不是

g++ -std=c++0x main.cpp -o test 

尝试像

g++ -std=c++0x main.cpp Database.cpp -o test 

这应该修复链接过程中缺失的引用。

0

您正在尝试编译没有数据库源文件的main.cpp。将数据库对象文件包含在g ++命令中,这些函数将被解析。

我几乎可以向你保证,这将成为一个快速的痛苦。我建议使用make来管理编译。

1

您还需要编译Database.cpp,并将两者连接在一起。

此:

g++ -std=c++0x main.cpp -o test 

尝试编译main.cpp一个完整的可执行文件。由于Database.cpp代码是从来不碰,你会得到链接错误(你喊成是从来没有定义的代码)

而且这样的:

g++ -std=c++0x main.cpp Database.cpp -o test 

编译两个文件到可执行

最后选项:

g++ -std=c++0x main.cpp Database.cpp -c 
g++ main.o Database.o -o test 

首先将两个文件编译成独立的对象fiels(的.o),然后将它们链接在一起成一个单一的可执行文件。

您可能想了解C++中的编译过程是如何工作的。