FranXh
FranXh

Reputation: 4771

Including gtest libraries in Makefiles for unit test files:

I am currently learning how to make and use MakeFiles for programs in C++. I have been able to create and run Makefiles for normal .cpp classes but I am having a problem with test classes. For testing I am using Gtest in Code::Blocks, and in my Test_A.cpp file in the "Linker Settings" I add:

 /usr/lib/libgtest.a
 /usr/lib/libgtest_main.a

and for the other linker options I put "-pthread". I know that in some way those libraries need to be added in the makefile, but I cannot figure how. I originally thought they need to be added in line 3, but everything I try returns thousands of lines of error of type:

 undefined reference to `testing::Test::TearDown()
 undefined reference to `testing::Test::~Test()  etc....

My makefile:

1. all: Test

2. Test_A.o: Test_A B.h
3.      g++ -c Test_A.cpp -o Test_A.o

4. Test: Test_A.o
5.      g++ -o Test Test_A.o

6. clean:
7.      rm -rf *o *~

Upvotes: 5

Views: 12231

Answers (2)

Tuxdude
Tuxdude

Reputation: 49473

You would need to pass the list of library names to the linker when building the final binary. LDFLAGS is a variables used in Makefiles to indicate the list of flags passed to the linker.

  • To link against a library libabc.a or libabc.so, you need to pass the linker flag as -labc.

  • To specify the location of the libraries, you need to use the -L flag. Note that the linker also searches the directories in LD_LIBRARY_PATH for your libraries in addition to the directories defined in /etc/ld.so.conf.

Although -L/usr/lib is optional in your case, (since your distro should have configured the ld.so.conf to pick up libraries from /usr/lib already), I've shown it below just in case you want to change it to a different location.

LDFLAGS := -lpthread -lgtest -lgtest_main -L/usr/lib

all: Test

Test_A.o: Test_A B.h
     g++ -c Test_A.cpp -o Test_A.o

Test: Test_A.o
     g++ -o Test Test_A.o $(LDFLAGS)

clean:
     rm -rf *o *~

Upvotes: 8

Vaughn Cato
Vaughn Cato

Reputation: 64308

Libraries are added on the link line:

g++ -o Test Test_A.o /usr/lib/libgtest.a /usr/lib/libgtest_main.a -lpthread

Upvotes: 8

Related Questions