【问题标题】:C++ #include not workingC++ #include 不起作用
【发布时间】:2014-07-15 20:13:48
【问题描述】:

我试图在 C++ 中包含这样的函数,但我不明白为什么它不起作用。我有 3 个文件。

test.cc

int test() {
  std::cout << "This is a test" << std::endl;
}

test.h

int test();

ma​​in.cc

#include "test.h"

int main() {

    test();
    return 0;
}

这是我得到的错误和我使用的命令。

c++ main.cc -o main
Undefined symbols for architecture x86_64:
  "test()", referenced from:
      _main in main-12ba52.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

【问题讨论】:

  • 您遇到的错误是什么?请张贴。我怀疑这是链接器问题,而不是编译器问题。
  • 你得到什么错误?
  • include 没有问题,只要列出test.cc 进行编译,但它不会编译。 std::cout 未声明。您必须在test.cc#include &lt;iostream&gt;
  • test.cc 缺少一些#includes
  • c++ main.cc -o main 仅编译 main.cc。您还需要将test.cc 编译成test.o,然后将test.omain.o 链接到一个可执行文件中。

标签: c++ header include


【解决方案1】:

这是罪魁祸首。

c++ main.cc -o main

你需要链接test.o。

c++ main.cc test.cc -o main

【讨论】:

    【解决方案2】:

    假设您正确使用编译器,请尝试在您的 test.cc 文件顶部包含 "test.h"

    #include "test.h"
    
    int test() {
       std::cout << "This is a test" << std::endl;
    }
    

    编译:

    g++ main.cc test.cc -o main
    

    【讨论】:

      【解决方案3】:

      您应该将以下内容添加到test.cc

      #include "test.h"
      #include <iostream>
      

      并确保您正在构建/链接test.cc

      【讨论】:

      • 我试过了,它仍然给我链接器错误。
      • 刚刚编辑说您需要确保链接到它。
      【解决方案4】:

      函数 test 的定义具有未定义的行为,因为它虽然返回类型为 int,但没有返回值

      int test() {
        std::cout << "This is a test" << std::endl;
      }
      

      由于您没有报告错误是什么,我认为问题在于您没有包含在项目文件 test.cc 中。您必须将它与文件 main.cc 一起链接,链接器才能找到 test 的定义。

      【讨论】:

      • 感谢您的回答,我实际上并没有意识到我的功能是错误的。问题是我遇到了链接器错误。
      • @Francis 您必须将两个模块链接在一起,链接器才能找到 test 的定义。
      猜你喜欢
      • 2023-04-06
      • 2015-02-20
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      相关资源
      最近更新 更多