编译和链接C代码调用C ++函数

时间:2013-03-13 17:44:30

标签: c++ c

从C代码调用C ++方法时遇到问题。我需要在C ++代码中调用的方法不在类中。我正在尝试设置一个简单的示例,我有以下文件:

//header.h
#ifdef __cplusplus
#include <iostream>
extern "C" {
#endif
int print(int i, double d);
#ifdef __cplusplus
}
#endif

//ccode.c
#include "header.h"

main() {
        printf("hello");
        print(2,2.3);
}

//cppcode.cc
#include "header.h"
using namespace std;
int print(int i, double d)
{
    cout << "i = " << i << ", d = " << d;
}

可能我的错误在于我正在尝试编译和链接它的方式。我正在做以下事情:

g++ -c cppcode.cc -o cppcode.o

没关系。

gcc ccode.c cppcode.o -o ccode

这里我收到以下错误:

cppcode.o: In function `print':
cppcode.cc:(.text+0x16): undefined reference to `std::cout'
cppcode.cc:(.text+0x1b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
cppcode.cc:(.text+0x28): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(int)'
cppcode.cc:(.text+0x35): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
cppcode.cc:(.text+0x42): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(double)'
cppcode.o: In function `__static_initialization_and_destruction_0(int, int)':
cppcode.cc:(.text+0x6b): undefined reference to `std::ios_base::Init::Init()'
cppcode.cc:(.text+0x70): undefined reference to `std::ios_base::Init::~Init()'
collect2: ld returned 1 exit status

我认为这是因为我正在使用C编译器。编译和链接这个小例子的正确方法是什么? 我的想法是运行C代码并调用C ++函数,而不必在C中重写它们。提前感谢您的帮助!

我使用的是Ubuntu 12.04,gcc版本4.6.3

3 个答案:

答案 0 :(得分:2)

您需要链接C ++运行时库。

gcc ccode.c cppcode.o -o ccode -lstdc++

答案 1 :(得分:1)

您应该单独编译和链接。使用g++进行链接以获得正确的标准库。

g++ -c cppcode.cc -o cppcode.o
gcc -c ccode.c -o ccode.o
g++ ccode.o cppcode.o -o ccode

答案 2 :(得分:0)

g ++编译器自动将您的程序与标准cpp库链接。 使用gcc编译时,链接器可以找到对它的引用。 你有两个选择。 一种是用g ++编译c文件。第二是强制标准cpp库的链接。

这是用gcc指南写的: -static-的libstdc ++

When the g++ program is used to link a C++ program, it normally automatically links against libstdc++. If libstdc++ is available as a shared library, and the -static option is not used, then this links against the shared version of libstdc++. That is normally fine. However, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link. The -static-libstdc++ option directs the g++ driver to link libstdc++ statically, without necessarily linking other libraries statically.

运行以下命令:

gcc ccode.c cppcode.o -o ccode -lstdc++