C++ 如何编写混合C和C++的makefile
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8653860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to write makefile mixing C and C++
提问by Dan
In this Makefile, I don't know how to compile out c objects in the same Makefile mixing C and C++. If I first compile the C objects and then run this Makefile, it works. Can anyone help to fix it for me? Thanks in advance!
在这个 Makefile 中,我不知道如何在混合 C 和 C++ 的同一个 Makefile 中编译出 c 对象。如果我首先编译 C 对象,然后运行这个 Makefile,它就可以工作。任何人都可以帮我修复它吗?提前致谢!
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)
回答by paulsm4
G++ can and will compile both .c and .cpp source files just fine.
G++ 可以并且会编译 .c 和 .cpp 源文件就好了。
What you reallyneed to do is add dependencies for "server" target. For example:
您真正需要做的是为“服务器”目标添加依赖项。例如:
OBJ = net.o hiredis.o sds.o async.o
...
all: server
server: $(OBJ)
There are some really good tips in this Howto.
这个 Howto 中有一些非常好的技巧。
回答by drodil
You can do that by compiling first the C files and then straight after the CPP files. This might work (at least worked in one of my projects):
您可以通过先编译 C 文件然后直接编译 CPP 文件来做到这一点。这可能有效(至少在我的一个项目中有效):
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 proper way to do it :)
如果您看到更合适的方法,请随时更改它:)