Question

I am new to makefiles and I am developing a (non-executable) library in C++.

Additionally to the library I have (executable) unit tests and an (executable) demo program. I would now like to be able to compile the unit tests and the demo program using make.

What is conceptually the correct way of doing this?

  1. Does the library have a makefile which just generates a library (.a) file which is then linked to the demo-program and the unit tests in their corresponding makefiles, i.e., do I have 3 makefiles? Would it still be possible to create the executable in only one step?

  2. Do only the demo-program and the unit tests have a makefile each?

Was it helpful?

Solution

You have not specified a development environment (IDE) and mentioned in the comments that you want this to be a more conceptual problem, so here is a way to organize this that is not specific to any IDE. I have actually done this before when developing static libraries.

First, you create your library project with its own makefile and ensure it compiles correctly. You will need a .a file as its output.

Next, your unit tests and demo program are all sister projects to the static library. The structure looks like this:

root
|
+-- library
|   |
|   +-- include
|   |
|   +-- bin
|
+-- demo program
|
+-- unit tests

Your other projects add "../library/include" to the include path. All modern compilers allow you to do this on the command line. In a similar way, you add "../library/bin" to the linker path. That way the linker can find the .a file.

Each project has its own makefile and its own IDE project files. They are separate, but used together. In an IDE you would set project dependencies so the library is built first.

Next, you can add a "master" makefile at the root level that simply goes into each subdirectory and builds each project using the makefile found therein. If you set up the makefile correctly it will also be sure to build in the correct order, all in one (user) step. Since this is the Internet, someone else has already said how to do this better than I can:


Note: this same design works when using other build environments such as Ant and Maven, and other compiled languages as well. I have used this structure for a variety of combinations of languages and build tools.

Licensed under: CC-BY-SA with attribution
scroll top