Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write makefile mixing C and C++

Tags:

c++

c

makefile

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!

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)
like image 534
Dan Avatar asked Dec 28 '11 09:12

Dan


People also ask

What does $() mean in makefile?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.

How Makefiles can be used to manage large C projects?

Makefile is a set of commands (similar to terminal commands) with variable names and targets to create object file and to remove them. In a single make file we can create multiple targets to compile and to remove object, binary files. You can compile your project (program) any number of times by using Makefile.


1 Answers

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

What you really need 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.

like image 108
paulsm4 Avatar answered Sep 29 '22 16:09

paulsm4