c++ - 在 C++ 中包含 C 代码

标签 c++ c g++

我正在尝试将 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++ 程序如下所示:

test1.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 header 和函数如下所示:

sample1.h

#include <stdio.h>

double add(const double a);

sample1.c

#include "sample1.h"

double add(const double a)
{
    printf("Hello World\n");

        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

关于c++ - 在 C++ 中包含 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13477807/

相关文章:

c realloc,大小的真正含义是什么

c - 通过指针访问结构

c++ - 零成本异常处理 vs setjmp/longjmp

c++ - gcc 允许未初始化的 constexpr

c++ - 如何使用 boost 预处理器生成访问器?

c - C : Consult SEXP PROTECT Stack Height 中的 R 扩展

c++ - C 程序获得不同的输出?这个程序应该输出什么?

c++ - 编译错误 Undefined symbols for architecture x86_64 :

C++ 初学者,第一个程序。寻找速度和距离

c++ - 如何在旧 OS X 上运行使用新 C++ 标准库编译的软件