Search code examples
c++makefilegoogletest

gtest - undefined reference to `testing::InitGoogleTest(int*, char**)'


I'm trying to create makefile and compile simple example of gtest but I get the error:

g++ main.o -o exampleOutput main.o: In function main': main.cpp:(.text+0x1e): undefined reference to testing::InitGoogleTest(int*, char**)' collect2: error: ld returned 1 exit status make: *** [output] Error 1

This the main.cpp:

#include <iostream>
#include "gtest/gtest.h"

using namespace std;

int main(int argc, char **argv)
{
    cout << "This is test" << endl;
    testing::InitGoogleTest(&argc, argv);
    return 0;
}

This is the makefile:

INCLUDE = -I/usr/include/
LIBPATH = -L/usr/lib/

output: main.o 
    g++ main.o  -o exampleOutput

main.o: main.cpp
    g++ -c main.cpp $(INCLUDE)  $(LIBPATH) -lgtest -lgtest_main  -pthread

The header files (of Gtest) are located in /usr/include/gtest and the lib files are located in /usr/lib.

What am I doing wrong?

Thanks.


Solution

  • The -lgtest and -lgtest_main arguments should be passed when linking exampleOutput, not when compiling main.o. The reason it works with the command in your comment is that that command is doing both steps in one go, whereas your makefile is not.

    The makefile is also incorrect in that the target is named only output whereas the command actually produces exampleOutput, so this command will always be executed even when it is not needed, because the file named output that it is expecting will never actually be produced...