Chris
Chris

Reputation: 279

Linking issue with C++ static libraries

I have 2 static libraries and I am building 1 executable that links these two libraries. This code compiled/ran fine until I moved the Crc function from library2 to library1. In library1 I have defined a function

uint16_t Crc16(const std::vector<uint8_t> &data);

In library2 I have a function

uint16_t MyClass::CalcChecksum()
{
    std::vector<uint8_t> payload(rawData.begin()+1, rawData.end()-FOOTER_SIZE);
    return Crc16(payload);
}

When I link the executable I am getting a "Undefined reference to `Crc16'. My link line is

g++ -rdynamic -Wl,-rpath,/home/chris/Qt5.3.0/5.3/gcc_64 -Wl,-rpath,/home/chris/Qt5.3.0/5.3/gcc_64/lib -o MyExecutable main.o server.o client.o service.o userserver.o pluginloader.o plugin.o moc_server.o moc_client.o moc_userserver.o moc_pluginloader.o moc_plugin.o   -L/home/chris/Dev/ProductName/build-ProductName-Desktop_Qt_5_3_0_GCC_64bit-Debug/MyExecutable/../StaticLibrary1/ -lStaticLibrary1 -L/home/chris/Dev/ProductName/build-ProductName-Desktop_Qt_5_3_0_GCC_64bit-Debug/MyExecutable/../StaticLibrary2/ -lStaticLibrary2 -ldl -L/home/chris/Qt5.3.0/5.3/gcc_64/lib -lQt5Network -lQt5Core -lpthread

When I check the exports for libray1 I get this:

nm lib1.a | grep -i crc
000000000000041d T Crc16

and lib2 I get this:

nm lib2.a | grep -i crc
                 U Crc16

The actual error that I get is

/home/chris/Dev/ProductName/build-ProductName-Desktop_Qt_5_3_0_GCC_64bit-Debug/MyExecutable/../StaticLibrary2//libStaticLibrary2.a(message.o): In function `Device::Message::CalcChecksum()':
/home/chris/Dev/ProductName/ProductName/StaticLibrary2/message.cpp:392: undefined reference to `Crc16'

The fact that library1 has the function defined, and library2 has the function marked as undefined makes sense. What doesn't make sense is when linking an executable it complains that the function is undefined.

Thanks, Chris

Upvotes: 0

Views: 175

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

Since library2 depends on library1, it needs to be listed first on the link line. Reverse the order and you should be good to go.

Upvotes: 2

Related Questions