I am using cmake for the first time and was trying to add snappy-c to my c++ project. I compiled the snappy-c library using the Makefile in its repo. I was hoping that adding the snappy.o to my CMakeLists.txt would allow me to use the snappy library. Unfortunately, that gives me an undefined reference error. How can I correctly add snappy-c to my c++ project?
My directory structure is
server-side
├── src
│── common_main.cpp
├── include
└── libs/snappy-c
This is my CMakeLists.txt file
cmake_minimum_required(VERSION 3.5)
add_definitions(-std=c++11)
# include public headers
include_directories("include" ${CMAKE_CURRENT_SOURCE_DIR}/libs/snappy-c)
# recursively add .cpp files to the SOURCES variable
file(GLOB_RECURSE SOURCES "src/*.cpp" main.cpp)
# create executable using SOURCES
add_executable(common-main ${SOURCES})
target_link_libraries(
common-main
${CMAKE_CURRENT_SOURCE_DIR}/libs/snappy-c/snappy.o
)
find_library(LIBRT rt)
if(LIBRT)
target_link_libraries(common-main ${LIBRT})
endif()
The code for which I get undefined reference is
#include <iostream>
#include "snappy.h"
int main(){
struct snappy_env env;
snappy_init_env(&env);
}
On running make VERBOSE=1
, I get the following output
cd /home/kakashi/Workbench/project/build/server-side && /usr/bin/cmake -E cmake_link_script CMakeFiles/common-main.dir/link.txt --verbose=1
/usr/bin/c++ -pthread CMakeFiles/common-main.dir/src/common_main.cpp.o CMakeFiles/common-main.dir/src/server_service.cpp.o CMakeFiles/common-main.dir/src/service_manager.cpp.o -o common-main ../../server-side/libs/snappy.o /usr/lib/x86_64-linux-gnu/librt.so
CMakeFiles/common-main.dir/src/common_main.cpp.o: In function `main':
common_main.cpp:(.text+0x399): undefined reference to `snappy_init_env(snappy_env*)'
collect2: error: ld returned 1 exit status
server-side/CMakeFiles/common-main.dir/build.make:200: recipe for target 'server-side/common-main' failed
make[2]: *** [server-side/common-main] Error 1
.Makefile:83: recipe for target 'all' failed
.
.
.
.