从C ++代码调用C函数
我有一个C函数,我想从C ++调用。 我不能使用“ extern "C" void foo() ”方法,因为C函数无法使用g ++编译。 但它使用gcc编译得很好。 任何想法如何从C ++调用函数? 
编译这样的C代码:
 gcc -c -o somecode.o somecode.c 
然后C ++代码是这样的:
 g++ -c -o othercode.o othercode.cpp 
然后用C ++连接器将它们连接在一起:
 g++ -o yourprogram somecode.o othercode.o 
 包含C函数的声明时,还必须告诉C ++编译器C头文件即将到来。 所以othercode.cpp开始于: 
 extern "C" { #include "somecode.h" } 
  somecode.h应该包含像这样的东西: 
  #ifndef SOMECODE_H_ #define SOMECODE_H_ void foo(); #endif 
(在这个例子中我使用了gcc,但是对于任何编译器来说,原理都是一样的,分别作为C和C ++来构build,然后将它们链接起来。
让我从其他答案和评论中收集点点滴滴,给你一个清晰分离的C和C ++代码的例子:
C部分:
foo.h :
 #ifndef FOO_H #define FOO_H void foo(void); #endif 
foo.c的
 #include "foo.h" void foo(void) { /* ... */ } 
 用gcc -c -o foo.o foo.c编译。 
C ++部分:
bar.cpp
 extern "C" { #include "foo.h" //a C header, so wrap it in extern "C" } void bar() { foo(); } 
 用g++ -c -o bar.o bar.cpp 
然后将它们链接在一起:
 g++ -o myfoobar foo.o bar.o 
  理由: C代码应该是简单的C代码,no #ifdef s代表“也许有一天我会用另一种语言调用它”。 如果一些C ++程序员调用你的C函数,那么他的问题是怎么做的,而不是你的。 如果你是C ++程序员,那么C头文件可能不是你的,你不应该改变它,所以处理unmangled函数名称(即extern "C" )属于你的C ++代码。 
 你当然可以自己写一个方便的C ++头文件,除了将C头文件包装成一个extern "C"声明。 
 我同意Falken教授的回答 ,但在Arne Mertz的评论之后,我想给出一个完整的例子(最重要的部分是#ifdef __cplusplus ): 
somecode.h
 #ifndef H_SOMECODE #define H_SOMECODE #ifdef __cplusplus extern "C" { #endif void foo(void); #ifdef __cplusplus } #endif #endif /* H_SOMECODE */ 
somecode.c
 #include "somecode.h" void foo(void) { /* ... */ } 
othercode.hpp
 #ifndef HPP_OTHERCODE #define HPP_OTHERCODE void bar(); #endif /* HPP_OTHERCODE */ 
othercode.cpp
 #include "othercode.hpp" #include "somecode.h" void bar() { foo(); // call C function // ... } 
然后你按照Falken教授的指示编译和链接。
 这是有效的,因为在使用gcc编译时,macros__cplusplus没有被定义,所以somecode.h包含的头文件在预处理之后就是这样的: 
 void foo(void); 
 当用g++编译时,定义了__cplusplus ,所以包含在其他othercode.cpp的头文件现在是这样的: 
 extern "C" { void foo(void); }