在linux中编译c++

Compile C++ in linux

本文关键字:c++ 编译 linux      更新时间:2023-10-16

我正在尝试在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

像这样的搜索到处都是,你可以想象。有什么建议我可以做些什么来解决这个问题吗?

这些都是链接器错误。它抱怨,因为它试图产生最终的可执行文件,但它不能,因为它没有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

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

您还需要编译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++的编译过程是如何工作的

代替

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

试试

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

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

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

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