首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在linux中编译C++

在linux中编译C++
EN

Stack Overflow用户
提问于 2011-04-21 23:02:01
回答 5查看 1.8K关注 0票数 0

我正在尝试用linux编译一个简单的应用程序。我的main.cpp看起来像这样

代码语言:javascript
复制
#include <string>
#include <iostream>
#include "Database.h"

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

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

代码语言:javascript
复制
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

正如你可以想象的那样,到处都在搜索这样的东西。我能做些什么来解决这个问题,有什么建议吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-04-21 23:04:29

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

试试这个:

代码语言:javascript
复制
g++ -std=c++0x main.cpp Database.cpp -o test

或者:

代码语言:javascript
复制
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
票数 5
EN

Stack Overflow用户

发布于 2011-04-21 23:04:27

由于引用了Database.h中的代码,因此必须在库中或通过目标文件Database.o (或源文件Database.cpp)提供实现。

票数 2
EN

Stack Overflow用户

发布于 2011-04-21 23:07:00

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

这一点:

代码语言:javascript
复制
g++ -std=c++0x main.cpp -o test

尝试将main.cpp编译为完整的可执行文件。由于Database.cpp中的代码从未接触过,因此会出现链接器错误(调用从未定义的代码)

还有这个:

代码语言:javascript
复制
g++ -std=c++0x main.cpp Database.cpp -o test

将这两个文件编译为可执行文件

最后一个选项:

代码语言:javascript
复制
g++ -std=c++0x main.cpp Database.cpp -c
g++ main.o Database.o -o test

首先将这两个文件编译为单独的对象字段(.o),然后将它们链接到单个可执行文件中。

您可能想要阅读C++中的编译过程是如何工作的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5745903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档