Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make file with source subdirectories

Tags:

makefile

My latest project is in C++ and I am using GNU Make. The project directory layout is as follows:

project
|-src
  |-subdir1
  |-subdir2 (containing tests)
|-doc
|-bin

I would like to be able to call make in the top level directory (i.e. need a makefile in the project directory) to compile all sources in both "src" subdirectories and place the resulting binaries in the "bin" directory.

What would be the best approach to do this? It would also be great if I didn't have to add a make rule for every source file, but just had one for all .cc and .h files in the directories.

like image 385
Jakob Avatar asked Mar 11 '11 13:03

Jakob


People also ask

How do I create a subdirectory file?

You can create a file in multiple directories by adding the directory names after the touch command. For example touch category/file1.

How do I get a list of files in a folder and subfolders into text file?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory.

How do I copy a file in subdirectories?

Copying Directories with cp Command To copy a directory, including all its files and subdirectories, use the -R or -r option.

How do you use mkdir with subdirectories?

Building a structure with multiple subdirectories using mkdir requires adding the -p option. This makes sure that mkdir adds any missing parent directories in the process. Use ls -R to show the recursive directory tree.


1 Answers

Make allows you to generalise your rules, so you won't need to create one for every file.

project
|-src
  |-subdir1
  |-subdir2 (containing tests)
|-doc
|-bin

You can try something like this:

#This finds all your cc files and places then into SRC. It's equivalent would be
# SRC = src/main.cc src/folder1/func1.cc src/folder1/func2.cc src/folder2/func3.cc

SRC = $(shell find . -name *.cc)

#This tells Make that somewhere below, you are going to convert all your source into 
#objects, so this is like:
# OBJ =  src/main.o src/folder1/func1.o src/folder1/func2.o src/folder2/func3.o

OBJ = $(SRC:%.cc=%.o)

#Tells make your binary is called artifact_name_here and it should be in bin/
BIN = bin/artifact_name_here

# all is the target (you would run make all from the command line). 'all' is dependent
# on $(BIN)
all: $(BIN)

#$(BIN) is dependent on objects
$(BIN): $(OBJ)
    g++ <link options etc>

#each object file is dependent on its source file, and whenever make needs to create
# an object file, to follow this rule:
%.o: %.cc
    g++ -c $< -o $@
like image 181
Sagar Avatar answered Sep 25 '22 02:09

Sagar