在C++中包含 C 代码
Including C Code in C++
我正在尝试将 C 代码包含在一个简单的 C++ 程序中,但我遇到了一个意想不到的问题 - 当我尝试编译程序时,g++ 给出了以下错误:
/tmp/cccYLHsB.o: In function `main':
test1.cpp:(.text+0x11): undefined reference to `add'
我搜索了一个解决方案并找到了本教程:
http://www.parashift.com/c++-faq/overview-mixing-langs.html
我的程序似乎没有区别,所以我有点迷茫......
我的C++程序如下所示:
测试1.CCP
#include <iostream>
using namespace std;
extern "C" {
#include "sample1.h"
}
int main(void)
{
int x= add(3);
cout << "the current value of x is " << x << endl;
return 0;
}
sample1 标头和函数如下所示:
样本1.h
#include <stdio.h>
double add(const double a);
样本1.c
#include "sample1.h"
double add(const double a)
{
printf("Hello Worldn");
return a + a;
}
对于编译,我首先使用 g++ 编译 test1.o,使用 gcc 编译 sample1.o(也尝试过 g++,但没有区别)
g++ -c test1.cpp
gcc -c sample1.c
这按预期工作。之后,我尝试像这样链接程序:
g++ sample1.o test1.o -o test
这是我得到上面提到的错误的地方
test1.cpp:(.text+0x11): undefined reference to `add'
我有一种感觉,我错过了一些重要的东西,但就是看不到它。
任何帮助都非常感谢!
问候
朱尔斯
它按预期工作。确保您没有意外地使用 g++
编译sample1.c
。
它适用于我的机器。试用 GCC 4.7.0
相关文章:
- 编译包含字符串的代码时遇到问题
- 在混合代码库中将C转换为C++时出现许多包含错误
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- 如何将外部代码包含在虚幻引擎4 C++项目中
- 如果代码包含多个复杂度循环,如何计算复杂度
- 如何使用 cmake 在代码中包含、构建和调试共享库 (.so)?
- 在 C++ 对象包装器中安全地包含 C 代码
- 为什么我的代码包含错误分段错误(核心转储)?
- 如何在此代码中包含 While 语句
- 在源文件中包含额外的调试信息,以便在代码::块中使用gdb进行调试
- 在Visual Studio代码中包含自定义c++库的问题
- 当我在结构中包含多个数组时,我的程序会跳过一堆代码
- C++:汇编代码包含断言结果
- 如何为代码包含负值?号码系统转换
- C++模板可以用于条件代码包含吗
- 如何将文件作为字符串和代码包含在cpp中
- C++代码包含错误
- c++宏:条件代码包含在表达式NOT语句中
- 端口C代码包含复数到c++
- 将模板代码包含在多个编译单元中,它将始终链接而不内联