Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Linux中编译C++_C++_Linux_Compiler Errors_Compilation - Fatal编程技术网

在Linux中编译C++

在Linux中编译C++,c++,linux,compiler-errors,compilation,C++,Linux,Compiler Errors,Compilation,我正在尝试用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是我的标头,并具有

我正在尝试用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.h中的代码,因此必须在库中或通过对象文件Database.o或源文件Database.cpp提供实现。

这些都是链接器错误。它抱怨是因为它试图生成最终的可执行文件,但它不能,因为它没有数据库函数的目标代码。编译器不会推断与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
而不是

g++ -std=c++0x main.cpp -o test
试试像这样的东西

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

这将修复链接过程中缺少的引用。

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

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

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

我想我们需要看到数据库.H.CPP文件,或者至少数据库类,以及命令行接口/实现。我怀疑这一点,但不确定。现在,我的数据库类还有其他包含项等等。确实有一种方法可以编译所有内容,而不必每次都键入它?脚本还是有g++选项?@Pete-你想要一个make文件。或者使用IDE为您的项目创建一个IDE。