Search code examples
c++static-linkingg++4.8

How to use CityHash128 in c++ code?


I am trying to use google's cityhash hashing function. I am unable to link it to my c++ code. I have installed cityHash and it has generated libcityhash.la, etc files in my /usr/local/lib.

I am setting LD_LIB_LIBRARY=/usr/local/lib, but it doesn't seem to link to these files.

CODE:

#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
    std::ifstream file("dev/urandom");
    char buff[4096];
    file.read(buff, 4096);
    const uint128 hashed = CityHash128(buff,4096);
    file.close();

}

Compiling:
g++ -o city cityHash.cpp

Error:
/tmp/cctSoHTX.o: In function main: cityHash.cpp:(.text+0x73): undefined reference to `CityHash128(char const*, unsigned long)' collect2: error: ld returned 1 exit status

I include "city.h" and trying to compile it as follows:

g++ -I /usr/local/include/ -L/usr/local/lib -llibcityhash.a cityHash.cpp -o city

But i m still getting :undefined reference to `CityHash128(char const*, unsigned long)' –


Solution

  • Ok, it's the good old "order makes a difference". Instead of:

    g++ -I /usr/local/include/ -L/usr/local/lib /usr/local/lib/libcityhash.a cityHash.cpp -o city
    

    you should do:

    g++ -I /usr/local/include/ -L/usr/local/lib  cityHash.cpp -o city -lcityhash
    

    (libraries and object files are processed in the order of appearance in the command line, and since none of the code so far has used anything from the library when you list it, nothing gets include from that library - then when you get to the actual code that does use it, you don't give the linker the library after it, so it can't find the symbol - note that this is dependant on the behaviour of the linker, so the same rules may not apply in for example a MS Visual Studio compiler/linker setup)