Skip to content

Instantly share code, notes, and snippets.

@BruceChen7
Last active February 15, 2019 13:30
Show Gist options
  • Save BruceChen7/a0823609863c2eb0e034604e35435c99 to your computer and use it in GitHub Desktop.
Save BruceChen7/a0823609863c2eb0e034604e35435c99 to your computer and use it in GitHub Desktop.
[#extern]#extern #__cplusplus
// 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__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment