为了在C中尝试C++代码包装,我使用了以下内容:header.h
#ifdef __cplusplus
extern "C"
#endif
void func();
Run Code Online (Sandbox Code Playgroud)
source.cpp
#include "header.h"
#include <iostream>
extern "C" void func()
{
std::cout << "This is C++ code!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
和source.c
#include "header.h"
int main()
{
func();
}
Run Code Online (Sandbox Code Playgroud)
为了编译和链接,我使用了以下序列:
g++ -c source.cpp
gcc source.c source.o -o myprog
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:从std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
source.cpp:(.text+0x1c): undefined reference tostd :: basic_ostream> :: operator <<(std :: basic_ostream>&(*)(std :: basic_ostream>&))'source.o:在函数__static_initialization_and_destruction_0(int, int)':
source.cpp:(.text+0x45): undefined reference tostd :: ios_base :: Init :: Init()'source.cpp :(.text + 0x4a):对std::ios_base::Init::~Init()'
source.o:(.eh_frame+0x12): undefined reference to__gxx_personality_v0的未定义引用'collect2:ld返回1退出状态
如何编译和运行这个简单的代码?它应该成为我未来发展的基础.
与g ++链接:
g++ -c source.cpp
g++ source.c source.o -o myprog
Run Code Online (Sandbox Code Playgroud)
或更好:
g++ -c source.cpp -o source_cpp.o
gcc -c source.c -o source_c.o
g++ -o myprog source_cpp.o source_c.o
Run Code Online (Sandbox Code Playgroud)
最好避免使用公共前缀源.{cpp,c},因为它会引起混淆.