CMake finds the correct library, but VC++ attempts

2019-07-18 15:57发布

问题:

I have a CMake module to locate FreeGLUT:

FIND_PATH(FREEGLUT_INCLUDE_DIR NAMES GL/freeglut.h)
FIND_LIBRARY(FREEGLUT_LIBRARY NAMES freeglut freeglut_static)

SET(FREEGLUT_LIBRARIES ${FREEGLUT_LIBRARY})
SET(FREEGLUT_INCLUDE_DIRS ${FREEGLUT_INCLUDE_DIR})

INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(FreeGLUT DEFAULT_MSG FREEGLUT_LIBRARY FREEGLUT_INCLUDE_DIR)

MARK_AS_ADVANCED(FREEGLUT_INCLUDE_DIR FREEGLUT_LIBRARY)

It works fine and locates freeglut_static.lib when I generate NMake Makefiles on Windows. I'm attempting to statically link FreeGLUT into my DLL:

FIND_PACKAGE(FreeGLUT REQUIRED)

ADD_LIBRARY(vti SHARED ${VTI_SOURCES})
ADD_DEFINITIONS("-DBUILD_VTI=1 -DFREEGLUT_STATIC=1")
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include ${FREEGLUT_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(vti ${FREEGLUT_LIBRARIES})

My source code builds correctly, but when it gets to the linking stage, VC++ fails with:

LINK : fatal error LNK1104: cannot open file 'freeglut.lib'

Which is strange since freeglut.lib isn't mentioned anywhere that I can see in the generated NMake makefiles. It should be trying to link with freeglut_static.lib, which CMake locates and sets in FREEGLUT_LIBRARIES.

What might be causing this?

回答1:

This is caused with pragma directives in FreeGLUT code (see freeglut_std.h). Using FREEGLUT_STATIC should really fix that for you, but I think you should pass it to CMake without quotes: ADD_DEFINITIONS(-DBUILD_VTI -DFREEGLUT_STATIC)