2
votes

I have a CMake file which does this:

find_package(Boost COMPONENTS system filesystem)

add_library(MyModule MODULE main.cpp)
target_include_directories(MyModule PUBLIC ${Boost_INCLUDE_DIRS})
target_link_libraries(MyModule Boost::system Boost::filesystem)

I'm using VS 2017 as my generator. When I generate the project file with cmake, it finds boost_system-vc141-mt-1_63.lib and I can see that it is in the linking rules of the vcxproj. However, when I try to compile I get this error:

LINK : fatal error LNK1104: cannot open file 'libboost_system-vc140-mt-1_63.lib

Note the different generators (vc140 vs vc141). I know my compiler has output the right values because I built boost from source, so I tried to just rename vc141 to vc140, but the error stayed the same. I also confirmed that vc140 is not referenced in the project file.

What's going on? How can I force boost to link to the correct version?

1
Added my solution below. Posted this so I could find it later when I run into the same problem. When I found the solution it's because a colleague mentioned "Auto link". I wouldn't have found the solution otherwise.Stewart

1 Answers

3
votes

When building with Visual Studio, boost has some pragma statements which do the linking for you. This is called "Auto-linking" and it over-rides any command-line arguments you may be passing to the linker.

The solution is to define BOOST_ALL_NO_LIB. This can be done in two ways:

  1. In source code before including boost headers as #define BOOST_ALL_NO_LIB.
  2. It could be added to your cmake file as: add_definitions("-DBOOST_ALL_NO_LIB").
  3. As of CMake 3.5: Use the disable_autolinking imported target:

    target_link_libraries(MyModule Boost::system Boost::filesystem Boost::disable_autolinking)