Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating two separate executables from a makefile (g++)

Tags:

c++

makefile

g++

Currently, I have my makefile set up to compile and make a fairly large project. I have written a second cpp file with main function for running tests. I want these to run separately, but build together and they use the same files. How is this accomplished?

edit: As reference, here is my current makefile. I'm not sure how to adjust it.

CC=g++
CFLAGS=-c -Wall -DDEBUG -g
LDFLAGS=
SOURCES=main.cpp Foo.cpp Bar.cpp Test.cpp A.cpp B.cpp C.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=myprogram

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@
like image 582
socks Avatar asked Mar 04 '11 08:03

socks


2 Answers

Normally you would just have multiple targets and do something like this:

.PHONY: all target tests

all: target tests

target: ...
    ...

tests: ...
    ...

Then you can just make (defaults to make all), or just make target or make tests as needed.

So for your makefile example above you might want to have something like this:

CC = g++
CFLAGS = -c -Wall -DDEBUG -g
LDFLAGS =
COMMON_SOURCES = Foo.cpp Bar.cpp A.cpp B.cpp C.cpp
TARGET_SOURCES = main.cpp
TEST_SOURCES = test_main.cpp
COMMON_OBJECTS = $(COMMON_SOURCES:.cpp=.o)
TARGET_OBJECTS = $(TARGET_SOURCES:.cpp=.o)
TEST_OBJECTS = $(TEST_SOURCES:.cpp=.o)
EXECUTABLE = myprogram
TEST_EXECUTABLE = mytestprogram

.PHONY: all target tests

all: target tests

target: $(EXECUTABLE)

tests: $(TEST_EXECUTABLE)

$(EXECUTABLE): $(COMMON_OBJECTS) $(TARGET_OBJECTS)
    $(CC) $(LDFLAGS) $^ -o $@

$(TEST_EXECUTABLE): $(COMMON_OBJECTS) $(TEST_OBJECTS)
    $(CC) $(LDFLAGS) $^ -o $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@
like image 89
Paul R Avatar answered Nov 13 '22 00:11

Paul R


Here's one way to do it:

CXXFLAGS += -std=c++11 -Wall -O3

all: myprog mytest

myprog.cpp: main.cpp
    cp -vf $< $@
myprog: myprog.o Foo.o Bar.o Test.o A.o B.o C.o

mytest.cpp: main.cpp
    cp -vf $< $@
mytest.o: CPPFLAGS += -DDEBUG
mytest.o: CXXFLAGS += -O0 -g
mytest: mytest.o Foo.o Bar.o Test.o A.o B.o C.o

This works because built-in rules exist for compiling objects from c++ source (%.o: %.cpp) and linking main programs (%: %.o).

Also note the use of target-specific values for the variables CPPFLAGS and CXXFLAGS.

like image 33
rubicks Avatar answered Nov 13 '22 00:11

rubicks