undefined reference 'shm_open', already add -lrt flag here

Solution 1:

Libraries at the end:

gcc test.c -o test -lrt

From GCC Link Options:

-llibrary
-l library
    Search the library named library when linking. 
    (The second alternative with the library as a separate argument
    is only for POSIX compliance and is not recommended.)

    It makes a difference where in the command you write this option;
    the linker searches and processes libraries and object files in the
    order they are specified.
    Thus, `foo.o -lz bar.o' searches library `z' after file foo.o but
    before bar.o. If bar.o refers to functions in `z', those functions
    may not be loaded.

Solution 2:

Change the compile line from

gcc -lrt test.c -o test

to

gcc test.c -o test -lrt

Solution 3:

In Expert C programming Page 108: <Handy Heuristic> Where to Put Library Options:Always put the -l library options at the rightmost end of your compilation command line. But it doesn't tell why, so i guess this is somewhat a rule?:)

Solution 4:

For those of you using super-auto-magical CMAKE like me, try to add:

target_link_libraries(your_binary_name PRIVATE librt.so)

to your CMakeLists.txt

Alternatively, replace PRIVATE for PUBLIC as needed..


If you have well established paths to libraries (e.g. all needed libs in /usr/lib), you may be fine with just stating in CMakeLists.txt:

set(CMAKE_CXX_FLAGS "-lrt")