ChrisW
ChrisW

Reputation: 5048

Finding directories in CMake

I'm trying to build a static library and use it for a compiling a fortran file. If I do:

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
add_library(mylib STATIC ${lib_src}/mylib.for)
file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
add_executable(bin/out ${PROJECT_SOURCE_DIR}/src/program.f)
target_link_libraries(bin/out mylib)

then it all works (note the library is built into the binary directory root, but the fortran is compiled into a subdirectory); but, if I do

set(archives ${PROJECT_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
add_library(mylib STATIC ${lib_src}/mylib.for)
find_library(mylib NAMES mylib PATHS ${archives})
file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
add_executable(bin/out ${PROJECT_SOURCE_DIR}/src/program.f)
target_link_libraries(bin/out mylib)

I get an error when I run cmake:

CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:   

mylib linked by target "bin/out" in directory /home/chris/project

If I leave out the final 2 lines, then the archive file does get written to the lib subdirectory, as libmylib.a as expected. If I do

set(archives ${PROJECT_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
add_library(mylib STATIC ${lib_src}/mylib.for)
find_library(mylib NAMES mylib PATHS ${archives})
include_directories(${archives})
set(libs ${libs} ${mylib})
file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
add_executable(bin/out ${PROJECT_SOURCE_DIR}/src/program.f)
target_link_libraries(bin/out {LIBS})

then the cmake command runs fine, but running make then generates compile errors (I know the set command and target_link_libraries variables are different cases - one of the things I don't understand is why this only fails when make is run, instead of cmake; if the variables are the same case, then I get the same error as above).

So, how can I get CMake to recognise my ${PROJECT_BINARY_DIR}/lib folder that is created during the CMake run? Can someone point out my (probably obvious) mistake?!

Upvotes: 0

Views: 946

Answers (1)

Guillaume
Guillaume

Reputation: 10971

You should not use find_library on one of your target, remove the line:

find_library(mylib NAMES mylib PATHS ${archives})

CMake already knowns about the mylib library as it's one of its target and calling find_library shadows the mylib variable.

You can keep you target_link_libraries call the same, as arguments can be either path to libraries or targets.r

Upvotes: 4

Related Questions