1

For the final step of creating the executable for my multimedia project I have something like this in one of my CMakeFiles.txt

add_executable(project a.cpp a.h)

if(WIN32)
    link_directories(${PROJECT_SOURCE_DIR}/lib/win)
    target_link_libraries(project opengl32 glfw3dll OpenAL32 alut ogg vorbis vorbisenc vorbisfile)
else()
    link_directories(${PROJECT_SOURCE_DIR}/lib/linux)
    target_link_libraries(project gl glfw3 openal alut vorbis ogg vorbisenc vorbisfile)
endif()

Inside the /lib/win directory are all the libraries I want to link to.

But every time tell cmake to build the project I get an error reading:

Error   LNK1104 cannot open file 'glfw3dll.lib' C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CMakeLists.txt    C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\LINK  1   

(Yes the file generated by the CMake Project of glfw is called "glfw3dll.lib")

I can hardlink against each library using:

target_link_libraries(project ${PROJECT_SOURCE_DIR}/lib/win/glfw3dll.lib)

for every single library but I guess CMake was not made to have me write all this ...

Also of course the corresponding libraries need to be copied to the final build and install directory to deploy the software. How do I tell CMake to do that?

salbeira
  • 2,375
  • 5
  • 26
  • 40
  • Possible duplicate of [Cmake cannot find library using "link\_directories"](https://stackoverflow.com/questions/31438916/cmake-cannot-find-library-using-link-directories) – Tsyvarev Dec 21 '18 at 20:46
  • The [second answer](https://stackoverflow.com/a/40554704/3440745) to the referenced question explains why `link_directories` doesn't work in your case: this command should come **before** `add_executable` for has an effect. – Tsyvarev Dec 21 '18 at 20:47

1 Answers1

1

The proper way to do this is to use FindLibrary first:

 find_library (glfw3dll_LIBRARY NAMES glfw3dll PATHS ${PROJECT_SOURCE_DIR}/lib/win)

And then use it:

target_link_libraries(project ${glfw3dll_LIBRARY})

This has a few advantages:

  • You know at CMake run time if the library was properly found,
  • As you have a variable, all the tests for platform are relegated to the set up, when you find all libraries.
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • This worked ... though what exactly is written to the variable? And how do I tell CMake to copy all libraries to the build or install directory for testing or deployment, as the library files are deemed missing when I launch the executable. – salbeira Dec 21 '18 at 14:37
  • In this case, it would be the full path, but hidden from you. Then CMake changes this path to be `-Lpath -llib` behind the scenes. To install the libraries, you need to add an install step with `INSTALL`. – Matthieu Brucher Dec 21 '18 at 14:42