没有创建对象文件

时间:2014-03-01 07:11:39

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

这是来自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

这里出了什么问题?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

您可能想在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项目。

答案 2 :(得分:2)

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

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