最近的项目需要在.c文件里面调用.cpp文件中的函数,以及在cpp中调用c文件函数,用到了c/c++混合编译,在这里记录一下。
makefile大致思路:
调用g++将所有.cpp文件编译成.o文件,调用gcc将所有.c文件编译成.o文件;
调用g++将所有的.o文件链接成可执行文件;
步骤很简单,唯一要注意的是在.c文件对应的头文件中一定需要加上
#ifdef __cplusplus
extern "C"
{
#endif
/* 函数声明代码块 */
#ifdef __cplusplus
}
#endif
否则在链接的时候会出现 undefined reference to 的错误。
示例 Makefile:
TARGET = pdif
OBJ_PATH = objs
PREFIX_BIN = ./
SRC = ./
CROSS_COMPILE=arm-linux-gnueabihf-
CC = $(CROSS_COMPILE)gcc
CPP = $(CROSS_COMPILE)g++
#include path
INCLUDES = -I ./$(SRC)app
#source path
SRCDIR = $(SRC)app
#buid to object files
#C_SOURCES = $(wildcard *.c)
C_SRCDIR = $(SRCDIR)
C_SOURCES = $(foreach d,$(C_SRCDIR),$(wildcard $(d)/*.c) )
C_OBJS = $(patsubst %.c, $(OBJ_PATH)/%.o, $(C_SOURCES))
#CPP_SOURCES = $(wildcard *.cpp)
CPP_SRCDIR = $(SRCDIR)
CPP_SOURCES = $(foreach d,$(CPP_SRCDIR),$(wildcard $(d)/*.cpp) )
CPP_OBJS = $(patsubst %.cpp, $(OBJ_PATH)/%.o, $(CPP_SOURCES))
default:init compile
#buid c files
$(C_OBJS):$(OBJ_PATH)/%.o:%.c
$(CC) -c $(CFLAGS) $(INCLUDES) $< -o $@
#buid c++ files
$(CPP_OBJS):$(OBJ_PATH)/%.o:%.cpp
$(CPP) -c $(CPPFLAGS) $(INCLUDES) $< -o $@
init:
$(foreach d,$(SRCDIR), mkdir -p $(OBJ_PATH)/$(d);)
test:
@echo "C_SOURCES: $(C_SOURCES)"
@echo "C_OBJS: $(C_OBJS)"
@echo "CPP_SOURCES: $(CPP_SOURCES)"
@echo "CPP_OBJS: $(CPP_OBJS)"
@echo "INCLUDES: $(INCLUDES)"
#link
compile:$(C_OBJS) $(CPP_OBJS)
$(CPP) $^ -o $(TARGET) $(LINKFLAGS) $(LIBS)
clean:
rm -rf $(OBJ_PATH)
rm -f $(TARGET)
install: $(TARGET)
cp $(TARGET) $(PREFIX_BIN)
uninstall:
rm -f $(PREFIX_BIN)/$(TARGET)
rebuild: clean init compile