4
votes

How I can write makefile for my structure:

/ --
   /bin
   /out
   /src --
        /dir1
        /dir2
        ...
        /dirN
   main.cpp

I want:

  • Compile all files recursively from /src directory
  • All .out files to /out, without src directory structure
  • Compile main.cpp with all .out files

I have both .c and .cpp files to compile and linking.

I tried:

${OBJ_DIR}/%.o: $(SRC_DIR)/%.cpp
    $(CXX) -c $< -o $@ ${CFLAGS}

But I now don't know how I can make all rule...

1
have you tried cmake? cmake.orgklm123
+1 for CMake, it is an elegant solution for that kind of problemSirDarius
@klm123 - hmm... but I can't find any good tutorial about it, I must first compile all files from /src to .o (g++ -c), and link all .o in one executable, with tons of libraries (like -lGL, -lpthread...)aso

1 Answers

2
votes

Here is a Makefile that I whipped up which I use in a lot of my projects:

# Compiler
CC   = g++
OPTS = -std=c++11

# Project name
PROJECT = foo_example_program

# Libraries
LIBS = -lpthread
INCS = -I./src/include

SRCS = $(shell find src -name '*.cpp')
DIRS = $(shell find src -type d | sed 's/src/./g' ) 
OBJS = $(patsubst src/%.cpp,out/%.o,$(SRCS))

# Targets
$(PROJECT): buildrepo $(OBJS)
    $(CC) $(OPTS) $(OBJS) $(LIBS) $(INCS) -o $@

out/%.o: src/%.cpp
    $(CC) $(OPTS) -c $< $(INCS) -o $@

clean:
    rm $(PROJECT) out -Rf

buildrepo:
    mkdir -p out
    for dir in $(DIRS); do mkdir -p out/$$dir; done

NOTE: Thinking back, I remember why I replicated the src directory structure - that is, if two files were named the same thing in multiple directories, they would overwrite one another. One solution to this would be to add some type of identifier to each object file. For instance, a number at the end. When a duplicate object file is found, you could name the object files 'object.1.o' and 'object.2.o' or something.