简体   繁体   中英

How to generate a Makefile with sources in sub-directories?

I have source located in the following manner.

/src/main.cpp
/src/hearts/hearts.cpp
/src/spades/spades.cpp
/src/oldmaid/oldmaid.cpp

How would I go about creating a makefile for this?

A simple way to do this would be to add all the source to a variable and use that variable in your make command. Here's a snippet with the relevant sections.

APP_SRC=src/main.cpp \
    src/hearts/hearts.cpp \
    src/spades/spades.cpp \
    src/oldmaid/oldmaid.cpp

CC=g++
CFLAGS= -Wall (and any other flags you need)


#
# Rules for building the application and library 
#
all: 
make bin


bin: 
$(CC)  $(CFLAGS) $(APP_SRC)

And here's a link to a good book to get started learning Make.

An excerpt from my Makefile. This searches for cpp files in the src directory and compiles them. You can add new files and make picks them automatically.

CC = g++  

all: compile
   find src -name '*.o' -print0 | xargs -0 $(CC) -o myExecutable

compile:
    find src -name '*.cpp' -print0 | xargs -0 $(CC) -c

clean:
    find src -iname '*.o' -print0 | xargs -0 rm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM