在C++中包含C代码

jul*_*les 15 c c++ g++

我正在尝试将C代码包含到一个简单的C++程序中,但我遇到了一个意想不到的问题 - 当我尝试编译程序时,g ++会出现以下错误:

/tmp/cccYLHsB.o: In function `main':
test1.cpp:(.text+0x11): undefined reference to `add'
Run Code Online (Sandbox Code Playgroud)

我搜索了一个解决方案并找到了本教程:

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;
}
Run Code Online (Sandbox Code Playgroud)

sample1标头和函数如下所示:

sample1.h

#include <stdio.h>

double add(const double a);
Run Code Online (Sandbox Code Playgroud)

sample1.c

#include "sample1.h"

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

        return a + a;
}
Run Code Online (Sandbox Code Playgroud)

对于编译,我首先使用g ++编译test1.o,使用gcc编译sample1.o(尝试使用g ++但没有区别)

g++ -c test1.cpp

gcc -c sample1.c
Run Code Online (Sandbox Code Playgroud)

这按预期工作.之后我尝试链接这个程序:

g++ sample1.o test1.o -o test
Run Code Online (Sandbox Code Playgroud)

这是我得到上述错误的地方

test1.cpp:(.text+0x11): undefined reference to `add' 
Run Code Online (Sandbox Code Playgroud)

我觉得我错过了一些重要但却看不到的东西.

任何帮助都非常感谢!

问候

儒勒

chi*_*ill 7

它的工作方式与预期一致.确保你没有意外编译sample1.c使用g++.

  • 并且有一个简单的方法可以找到,运行`nm sample1.o`,`add`应该有1个非破坏符号,如果没有,那么除了`gcc -c sample1.c`之外的其他东西生成了sample1.o文件. (2认同)
  • 非常感谢,就是这个问题!我用 g++ 编译了这两个文件 (2认同)