從我的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
你有一個c + +依賴;你應該使用'gcc'來構建'ccode.o',然後使用'g ++'將.o文件鏈接在一起。 – Joe 2013-03-13 17:49:08
請勿在其他標題內包含標題,甚至標準標題。除非他們明確定義了頭文件中需要的類型/常量*。 – StoryTeller 2013-03-13 17:51:38
@StoryTeller:謝謝你的提示,我會修復這個問題 – natascha 2013-03-13 18:05:04