在我的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
最佳答案
您需要链接C++运行库。
gcc ccode.c cppcode.o -o ccode -lstdc++