Search code examples
c++makefilelinkercatch-unit-test

Why do we need to compile a main test file separately with Catch?


I wrote the following Makefile (which does work as expected):

CXX2 = clang++
CXXFLAG2 = -std=c++11 -c -g -O0 -Wall -Wextra
LD2 = clang++
LDFLAG2 = -std=c++11

testing: data_test.o test_main.o dataframe.o csvreader.o course.o
    $(LD2) $^ $(LDFLAG2) -o $@

data_test.o: test/data_test.cpp
    $(CXX2) $< $(CXXFLAG2)

test_main.o: test/test_main.cpp
    $(CXX2) $< $(CXXFLAG2)

dataframe.o: src/DataFrame.cpp src/CSVReader.cpp src/Course.cpp
    $(CXX2) $< $(CXXFLAG2)

In my test_main.cpp file, I only have the following lines:

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

I tried seeing if in my Makefile I could replace the test rule as follows:

data_test.o: test/data_test.cpp test/test_main.cpp
    $(CXX2) $< $(CXXFLAG2)

However, I get an "_main", referenced from: implicit entry/start for main executable error. To me, it seems like it should work fine just including test_main.cpp as a dependency for my actual tests. Is there a reason why this main file needs to be compiled as its own .o file?


Solution

  • From the make manual:

    $<
    The name of the first prerequisite. If the target got its recipe from an implicit rule, this will be the first prerequisite added by the implicit rule (see Implicit Rules).

    Thus the rule bellow compiles data_test.cpp and does not compile test_main.cpp:

    data_test.o: test/data_test.cpp test/test_main.cpp
        $(CXX2) $< $(CXXFLAG2)