问题
I am new to cmake
and know this question has been asked before, but still cannot find what I am doing wrong. I have an external library with folders /include
and lib
. The /include
folder contains all the headers (.h
) and the /lib
folder contains all the source (.c
) files.
In my project I have this CMakeList.txt
file:
cmake_minimum_required(VERSION 3.7)
project(FirstAttempt)
set(CMAKE_CXX_STANDARD 11)
set (EXTRA_LIBS "D:\\libtrading")
include_directories(${EXTRA_LIBS}/include)
link_directories(${EXTRA_LIBS}/include)
set(SOURCE_FILES main.cpp)
add_executable(FirstAttempt ${SOURCE_FILES})
target_link_libraries (FirstAttempt ${EXTRA_LIBS}/lib)
I know that I have to use target_link_libraries
to link the source files of the library to my project, but certainly something is missing, but what? I am still receiving the error undefined reference to xxxxxx
.
The library I am trying to include in my project is https://github.com/libtrading/libtrading.
回答1:
Well, I'll try.
First, seems that you are calling link_directories()
on the folder which contains header files, while it should be used in order to specify the path where to search libraries for.
Second, target_link_libraries()
takes the absolute path of the shared/static library file as the second argument, while you are passing the directory path (well, it seems so).
target_link_libraries()
doesn't link to the "source files of the library", - it links to the compiled shared/static library blob.
And, I would also recommend you to save the name of the executable to the variable so that you wouldn't be able to mistype the target name, like so:
set(TARGET FirstAttempt)
add_executable(${TARGET})
回答2:
As you know, we need all source files to compile. So we need to point out Cmake know where/what are source files.
I think you should add all sources files like this
file(GLOB SOURCES_FILES "lib/*.c" main.cpp)
to add all .c files.
Or, you can add all lib/*.c files separately
file(SOURCES_FILES_LIBS "lib/*.c")
set(SOURCES_FILES main.cpp)
add_executable(FirstAttempt ${SOURCES_FILES_LIBS} ${SOURCES_FILES})
来源:https://stackoverflow.com/questions/45626584/cmake-undefined-reference-to