Peter
Peter

Reputation: 239

How to add Windows libraries in CMake?

I want to include ws2_32.lib to my application but CMake tacks on -l to the project properties.

...
add_executable(Executive ${exec_src})
target_link_libraries(Executive ws2_32)

So that is what my CMakeLists.txt file looks like, but when I check the VS2010 Linker Property page under "Input" it lists -lws2_32.lib. Why does it add the -l? And how can I remove that, because once I manually change it to read ws2_32.lib the project is able to link properly.

I tried the following: find_library(WIN_C ws2_32) but the result was NOTFOUND.

Upvotes: 5

Views: 10340

Answers (2)

Peter Russell
Peter Russell

Reputation: 243

Since my previous answer, I've found a better approach myself.

At the start of your CMAKE output are you seeing something like this?:

The C compiler identification is unknown
The CXX compiler identification is unknown

If so, it seems that CMake is not correctly determining your compiler - and so is not correctly work out how to pass linker arguments.

In my case it looks like it was being confused by the suite of tools I have installed. I have various versions of the VS2010 express tools, and also the TFS Team Explorer - which installs the Visual Studio shell. It looks like CMake was seeing the presence of devenv.exe and assuming that I therefore have a full visual studio.

You can fix this by specifying the CMAKE_MAKE_PROGRAM variable - at the commandline with -D CMAKE_MAKE_PROGRAM or in the GUI by ticking the advanced tickbox and finding the entry. I needed to change it from C:/PROGRA~2/MICROS~1.0/Common7/IDE/devenv.com to C:/PROGRA~2/MICROS~1.0/Common7/IDE/VCExpress.exe - note the forward slashes!

Once I'd done that I didn't need to do the find_library thing any more.

Upvotes: 2

Peter Russell
Peter Russell

Reputation: 243

I encountered the same problem, using the Visual Studio 2010 generator and CMake 2.8.11.2. In my case I was trying to link with wininet.lib. I assume it's a bug in CMake, and I spent quite a long time looking for a workaround. Eventually I found that the following works:

Use the find_library command to find the absolute path of the .lib file, and assign it to a variable. Then use that variable in your target_link_libraries command. In your case, it would look like this:

find_library(ws2_32_LIBRARY_PATH ws2_32)
add_executable(Executive ${exec_src})
target_link_libraries(Executive ${ws2_32_LIBRARY_PATH})

Hope that saves someone some time.

Upvotes: 3

Related Questions