C中调用C++函数
文件结构:
- src
- c
- main_c.c
- cpp
- main_cpp.c
- inc
- main_c.h
- main_cpp.h
- c
- obj
- makefile
// src/c/main_c.c
#include "main_cpp.h"
#include "main_c.h"
int main_c(){
return 0;
}
int c_add(int a, int b){
return a + b;
}
int c_sub(int a, int b){
return a - b;
}
// src/inc/main_c.h
#ifndef __MAIN_C_H__
#define __MAIN_C_H__
#ifdef __cplusplus
extern "C" {
#endif
int main_c(void);
int c_add(int a, int b);
int c_sub(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
// src/cpp/main_cpp
#include "asm.h"
#include "main_cpp.h"
#include "main_c.h"
int main_cpp(void){
int a = 10;
int b = 20;
int c = c_add(a, b);
int d = c_sub(a, b);
return 0;
}
// src/inc/main_cpp.h
#ifndef __MAIN_CPP_H__
#define __MAIN_CPP_H__
#ifdef __cplusplus
extern "C" {
#endif
int main_cpp(void);
#ifdef __cplusplus
}
#endif
#endif
Inc = -Isrc/inc
OBJINC = obj
ASM = gcc
ASMFLAGS = -ggdb -m32
CC = gcc
CFLAGS = -ggdb -m32
CPP = g++
CPPFLAGS = -ggdb -m32
LD = ld
LDFLAGS = -m elf_i386
all:
$(CPP) $(Inc) $(CPPFLAGS) -c ./src/cpp/main_cpp.cpp -o $(OBJINC)/main_cpp.o
$(CC) $(Inc) $(CFLAGS) -c ./src/c/main_c.c -o $(OBJINC)/main_c.o
$(LD) $(LDFLAGS) -e main_cpp $(OBJINC)/main_c.o $(OBJINC)/main_cpp.o
clean:
rm $(OBJINC)/*.o
gdb:
gdb a.out --tui