我正在尝试用linux编译一个简单的应用程序。我的main.cpp看起来像这样
#include <string>
#include <iostream>
#include "Database.h"
using namespace std;
int main()
{
Database * db = new Database();
commandLineInterface(*db);
return 0;
}其中Database.h是我的头文件,有一个对应的Database.cpp。编译时出现以下错误:
me@ubuntu:~/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正如你可以想象的那样,到处都在搜索这样的东西。我能做些什么来解决这个问题,有什么建议吗?
发布于 2011-04-21 23:04:29
这些都是链接器错误。它抱怨是因为它试图生成最终的可执行文件,但它不能,因为它没有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发布于 2011-04-21 23:04:27
由于引用了Database.h中的代码,因此必须在库中或通过目标文件Database.o (或源文件Database.cpp)提供实现。
发布于 2011-04-21 23:07:00
您还需要编译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首先将这两个文件编译为单独的对象字段(.o),然后将它们链接到单个可执行文件中。
您可能想要阅读C++中的编译过程是如何工作的。
https://stackoverflow.com/questions/5745903
复制相似问题