Building Multiple Programs

Instructions to use one makefile to build multiple programs from one code base. For example: you have code that is for a unit test project and code that is for your main program. You can't compile it into one program as the tests and "main" program each define a main function. So you need to build two separate programs.

These instructions are based on the MakeComplex project from the CS260 code repository. Use it if you want to be able to follow along exactly. The instructions assume you have a terminal open in that directory.

  1. Examine the code in MakeComplex. There are two separate files with main functions - programA.cpp and programB.cpp. Those represent two separate programs that both happen to use code from Answer.cpp. We need to build the two files into two separate programs.

  2. Create a file called MyMake and start with:

    	#make a directory to hold the build product 
    	mkdir -p build
    	#build MyProgram.exe to that directory
    	g++ -g -o build/ProgramA.exe programA.cpp Answer.cpp
    	g++ -g -o build/ProgramB.exe programB.cpp Answer.cpp
    	rm -rf build

    The two separate g++ commands each do a separate build. The first builds ProgramA.exe using programA.cpp and Answer.cpp. The second builds ProgramB.exe using programB.cpp and Answer.cpp.

    Note that programA does not use programB.cpp to build with and vice verse. Each program can only have one main function.

  3. Modify the MyMake to look like:

    all: ProgramA ProgramB
    ProgramA: makeDirectory
    	g++ -g -o build/ProgramA programA.cpp Answer.cpp
    ProgramB: makeDirectory
    	g++ -g -o build/ProgramB programB.cpp Answer.cpp
    	mkdir -p build
    	rm -rf build

    The default rule all lists ProgramA and ProgramB as prerequisites. This forces both of those rules to run and builds both programs.

    ProgramA and ProgramB each just build one of the two programs. They both have makeDirectory as a prerequisite to make sure that we check to make the directory.

    You can now build just one program by executing the command:

    make -f MyMake ProgramA


    make -f MyMake ProgramB