Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ makefile building multiple dll and project structuring

I have tried searching for an answer but to no avail, so given that my project has got the following structure

makefile
./src
   strings.cpp
   networking.cpp
./bin
   strings.dll
   networking.dll
./build
   strings.o
   networking.o
./include
   strings.h
   networking.h
./lib
   boost

I am very new to Makefiles and from the research I have done so far I have managed to get this together (not very complicated, I know)

CC = g++ 
SRC = src/strings.cpp
OUT = bin/strings.dll
OBJ = build/strings.o 
INC= -I include

all: strings.dll

strings.dll: strings.o
    $(CC) -shared -o $(OUT) $(OBJ) 

strings.o: $(SRC) 
    $(CC) $(INC) -DBDLL -c $(SRC) -o $(OBJ)

The issues/questions I have are

1- It always goes through the whole compilation process, even when I have not changed the source code ?

2- How could I make things more 'effective' ? I saw examples of people using wildcards and such, but I had difficulty following along. Could I use wildcards to begin with since I want separate dlls for each target ?

3 - Lets say I introduced algorithms.h and algorithms.cpp what would be the recommended way of including that in the build ?

Thanks for any help, really appreciate it

like image 369
Aj S Avatar asked Dec 29 '25 22:12

Aj S


1 Answers

First. Whole compilation process goes because make search for target "strings.dll" but build bin/strings.dll. So if you replace it to

bin/strings.dll: strings.o
     $(CC) -shared -o $(OUT) $(OBJ)

bin/strings.o: $(SRC) 
     $(CC) $(INC) -DBDLL -c $(SRC) -o $(OBJ)

build of targets (bin/strings.o and bin/strings.dll) will be performed only if prerequisite is changed.

Second - basically wildcards are used for search all files inside the directory something like this: $(whildcard *.cpp) evaluates to all cpp file inside the current directory. So you can write something like this:

all_sources = $(wildcard *.cpp)
all_objects = $(addprefix bin/,$(all_sources:.cpp=.o))

all: bin/strings.dll

bin/strings.dll: $(all_objects)
    <how to build strings.dll from objects>

bin/%.o: %.cpp
    <how to build objects inside bin dir from cpp of current dir>    

Third - makefile is not build system itself it is just a tool that has domain specific language. You can write your own build system using make. If you want ready build you better to study automake/cmake/... many of them.

Also it is good beginning to start using make tool. Don't stop and you will surprise how much power inside it.

like image 195
Dmitry Poroh Avatar answered Jan 01 '26 12:01

Dmitry Poroh