// call c function in cpp files
//cExample.h
#ifndef C_EXAMPLE_H
#define C_EXAMPLE_H
int add(int x,int y);
#endif
//cExample.c
#include "cExample.h"
int add( int x, int y ) {
return x + y;
}
// cppExample.cpp 一般放置头文件中,比如下面的例子
extern "C" {
#include "cExample.h"
}
int main(int argc, char* argv[]) {
add(2,3);
return 0;
}
//Generate cExample.o file
gcc -c cExample.c
g++ -c cppExample.cpp
g++ -o cExample.o cppExample.cpp -o main
// call cpp function in c
// cppExample.h
#ifndef CPP_EXAMPLE_H
#define CPP_EXAMPLE_H
extern "C" int add( int x, int y );
#endif
// cppExample.cpp
#include "cppExample.h"
int add( int x, int y ) {
return x + y;
}
// cExample.c
extern int add( int x, int y );
int main() {
add( 2, 3 );
return 0;
}
一个典型的例子
// 在C++中使用C
#ifndef __ASSERT_H__
#define __ASSERT_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <assert.h>
#define ASSERT(cond) assert(cond)
#ifdef __cplusplus
}
#endif
#endif // __ASSERT_H__
- __cplusplus This macro is defined when the C++ compiler is in use. https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html