在C++中包含 C 代码

Including C Code in C++

本文关键字:代码 包含 C++      更新时间:2023-10-16

我正在尝试将 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