【问题标题】:Compile C++ in linux在linux下编译C++
【发布时间】:2011-04-21 15:02:01
【问题描述】:

我正在尝试在 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|cpp) 文件,或者至少需要查看 Database 类和 commandLineInterface 接口/实现。

标签: c++ linux compiler-errors compilation


【解决方案1】:

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

【讨论】:

  • 我怀疑这一点,但不确定。现在我的数据库类有其他包含等等。当然有一种方法可以编译所有内容而不必每次都输入它?脚本还是有 g++ 选项?
  • @Pete - 你想要一个 make 文件。 gnu.org/software/make/manual/make.html 或者使用将为您的项目创建一个 IDE。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      代替

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

      试试类似的东西

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

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

      【讨论】:

        【解决方案5】:

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

        我几乎可以向你保证,这很快就会变得很痛苦。我建议使用 make 来管理编译。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          • 2011-08-09
          • 1970-01-01
          • 1970-01-01
          • 2023-03-22
          • 1970-01-01
          相关资源
          最近更新 更多