【问题标题】:Object file not being created未创建目标文件
【发布时间】:2014-03-01 07:11:38
【问题描述】:

这是来自 Richard Stevens 关于高级 Linux 编程的书。

所以当它教用 GCC,G++ 编译时, 我创建了一个名为 reciprocal 的文件夹,其中创建了以下文件,代码如下所示。

main.c:

#include <stdio.h>
#include "reciprocal.hpp"
int main (int argc, char **argv)
{
  int i;
  i = atoi (argv[1]);
  printf ("The reciprocal of %d is %g\n", i, reciprocal (i));
  return 0;
}

reciprocal.cpp:

#include <cassert>
#include "reciprocal.hpp"
double reciprocal (int i) {
  // I should be non-zero.
  assert (i != 0);
  return 1.0/i;
}

reciprocal.hpp:

#ifdef __cplusplus
extern "C" {
#endif
extern double reciprocal (int i);

#ifdef __cplusplus
}
#endif

所有三个文件都在同一个文件夹中。现在我在终端gcc -c main.c 中输入命令并创建了对象main.o 但是当我写g++ -c reciprocal.cpp 时它显示错误

reciprocal.cpp: In function ‘double reciprocal(int)’:
reciprocal.cpp:4:8: error: redefinition of ‘double reciprocal(int)’
reciprocal.cpp:4:8: error: ‘double reciprocal(int)’ previously defined here

这里出了什么问题?

【问题讨论】:

  • 为什么要编译reciprocal.cpp? main() 应该为您正在编译的文件定义。你没有 reciprocal.cpp 的 main()
  • 适用于g++ 4.8.2。 (修正#endi 错字后。)你使用的是哪个版本的g++
  • 感谢@leeduhem 我更新到 g++ 4.8.2 并且成功了 :) !

标签: c++ c gcc linker g++


【解决方案1】:

您正在将其编译为 C++。将其编译为 C 或转储 extern "C"

【讨论】:

  • 我不知道,但不知何故,任何一个选项都不起作用,我将它编译为 c,它不起作用然后转储 extern C,仍然显示相同的错误
【解决方案2】:

如果不存在,请在类 reciprocal.h 中添加标头保护,因为您在 main.cpp 和 reciprocal.cpp 中包含 reciprocal.h 两次,因此您将面临此错误。

 #ifndef RECIPROCAL_H
 #define RECIPROCAL_H
 // All code here
 #endif

【讨论】:

    【解决方案3】:

    您可能想要 reciprocal.cpp 中的以下内容:

    #include <cassert>
    #include "reciprocal.hpp"
    extern "C" double reciprocal (int i) {
      // I should be non-zero.
      assert (i != 0);
      return 1.0/i;
    }
    

    此外,如果您使用相同的语言编译这两个文件,则根本不需要那些 extern 子句。因此,您可以创建 main.cpp 和 reciprocal.cpp 并使用 g++ 编译它们,或者创建 main.c 和 reciprocal.c 并使用 gcc 编译它们。第一种情况是给一个 C++ 项目,第二种情况是给一个 C 项目。

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多