在 C++ 中包含 C 代码 [英] Including C Code in C++

查看:26
本文介绍了在 C++ 中包含 C 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to include C code into a simple C++ program but I ran into an unexpected problem - when I try to compile the program g++ gives the following error:

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

我搜索了一个解决方案,找到了这个教程:

I searched for a solution and found this tutorial:

http://www.parashift.com/c++-faq/概述混合语言.html

我的程序似乎没有什么不同,所以我有点迷茫......

There seems to be no difference to my program so I'm a bit lost...

我的 C++ 程序如下所示:

My C++ program looks like this:

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 标头和函数如下所示:

The sample1 header and function look like this:

sample1.h

#include <stdio.h>

double add(const double a);

sample1.c

#include "sample1.h"

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

        return a + a;
}

为了编译,我首先用 g++ 编译 test1.o,用 gcc 编译 sample1.o(也试过 g++,但没有区别)

For compilation I first compile a test1.o with g++ and sample1.o with gcc (tried g++ also but makes no difference)

g++ -c test1.cpp

gcc -c sample1.c

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

That works as expected. Afterwards I try to link the program like this:

g++ sample1.o test1.o -o test

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

This is where I get the error mentioned above

test1.cpp:(.text+0x11): undefined reference to `add' 

我感觉我错过了一些重要的东西,但就是看不到它.

I have the feeling that I'm missing something important but just can't see it.

非常感谢任何帮助!

问候

朱尔斯

推荐答案

它按预期工作.确保您没有使用 g++ 意外编译 sample1.c.

It works just as expected. Make sure you haven't accidentally compiled sample1.c with g++.

这篇关于在 C++ 中包含 C 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆