【发布时间】: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 并且成功了 :) !