How to write file mixing in C and C ++

In this Makefile, I don’t know how to compile c objects in the same mix of C and C ++ Makefile. If I compile C objects first and run this Makefile, it will work. Can anyone help fix this for me? Thank you in advance!

CXX = g++ CXXFLAGS = -Wall -D__STDC_LIMIT_MACROS SERVER_SRC = \ main.cpp SERVER_SRC_OBJS = ${SERVER_SRC:.cpp=.o} REDIS_SRC = \ $(HIREDIS_FOLDER)/net.c \ $(HIREDIS_FOLDER)/hiredis.c \ $(HIREDIS_FOLDER)/sds.c \ $(HIREDIS_FOLDER)/async.c REDIS_SRC_OBJS = ${REDIS_SRC:.c=.o} .SUFFIXES: .SUFFIXES: .o .cpp .cpp.o: $(CXX) $(CXXFLAGS) -I$(HIREDIS_FOLDER) \ -c $< -o $*.o all: server net.o: net.c fmacros.h net.h hiredis.h async.o: async.c async.h hiredis.h sds.h dict.c dict.h hiredis.o: hiredis.c fmacros.h hiredis.h net.h sds.h sds.o: sds.c sds.h server: $(SERVER_SRC_OBJS) $(REDIS_SRC_OBJS) mkdir -p bin $(CXX) $(CXXFLAGS) -o bin/redis_main \ -I$(HIREDIS_FOLDER) \ $(REDIS_SRC_OBJS) \ $(SERVER_SRC_OBJS) \ -lpthread \ -lrt \ -Wl,-rpath,./ .PHONY: clean clean: $(RM) -r bin/redis_main $(RM) ./*.gc?? $(RM) $(SERVER_SRC_OBJS) $(RM) $(REDIS_SRC_OBJS) 
+4
source share
2 answers

g ++ can and will compile both .c and .cpp source files just fine.

What you really need to do is add dependencies to the destination server. For instance:

 OBJ = net.o hiredis.o sds.o async.o ... all: server server: $(OBJ) 

There are some really good tips in this Howto .

+7
source

You can do this by compiling the C files first, and then immediately after the CPP files. This may work (at least it worked in one of my projects):

 CXX = g++ CC = gcc CFLAGS = -Wall -c CXXFLAGS = -Wall -D__STDC_LIMIT_MACROS OUTPUTDIR = ./bin/ MKDIR = mkdir -p $(OUTPUTDIR) OBJECTC = redis.o CSOURCES = \ $(HIREDIS_FOLDER)/net.c \ $(HIREDIS_FOLDER)/hiredis.c \ $(HIREDIS_FOLDER)/sds.c \ $(HIREDIS_FOLDER)/async.c CXXSOURCES = \ main.cpp all: server server: $(MKDIR) $(CC) $(CSOURCES) $(CFLAGS) -o $(OUTPUTDIR)$(OBJECTC) $(CXX) $(OUTPUTDIR)$(OBJECTC) $(CXXSOURCES) -o $(OUTPUTDIR)server .PHONY: clean clean: $(RM) -rf $(OUTPUTDIR) $(RM) ./*.gc?? $(RM) ./*.o 

Feel free to change it if you see a more correct way to do it :)

+5
source

Source: https://habr.com/ru/post/1388262/


All Articles