Linking project with statically build curl

泄露秘密 提交于 2019-12-23 10:57:05

问题


I'm doing small project in C++ with CMake and MinGW32, which requires libcurl library, but when i try to link statically build libcurl.a I get undefined reference errors

undefined reference to `_imp__curl_easy_init'
undefined reference to `_imp__curl_easy_setopt'
undefined reference to `_imp__curl_easy_perform'
undefined reference to `_imp__curl_easy_getinfo'
undefined reference to `_imp__curl_easy_strerror'

I have cURL source code in dep/curl and my source code in src folder. And this is how my project's CMakeLists.txt looks like:

project(ShutdownServer)
cmake_minimum_required(VERSION 2.8)
set(CMAKE_BUILD_TYPE "Release")
set(CURL_STATICLIB true)
set(BUILD_CURL_EXE false)

add_subdirectory(dep/curl)
set(TARGET_NAME "ShutdownServer")
set(LIBCURL_DIR ${PROJECT_SOURCE_DIR}/dep/curl)

aux_source_directory(src SRC_LIST)
add_executable(${TARGET_NAME} ${SRC_LIST})

find_path(LIBCURL_INCLUDE_DIR curl/curl.h HINTS ${LIBCURL_DIR}/include)
include_directories(${LIBCURL_INCLUDE_DIR})

add_dependencies(${TARGET_NAME} libcurl)

set(LIBS ${LIBS} ws2_32)
set(LIBS ${LIBS} iphlpapi)
set(LIBS ${LIBS} libcurl)

target_link_libraries(${TARGET_NAME} ${LIBS})

set(CMAKE_EXE_LINKER_FLAGS "-static -static-libgcc -static-libstdc++")

When I switch CURL_STATICLIB option to false, and build libcurl dynamically, project is build fine, but I'd rather had build all into one binary file. Can anybody please tell me what is wrong with this?


回答1:


You need to define CURL_STATICLIB when including curl.h, otherwise the compiler will think that you are trying to link against the dynamic version of the libcurl library.

If you examine curl.h, you can see the following lines:

/*
 * Decorate exportable functions for Win32 DLL linking.
 * This avoids using a .def file for building libcurl.dll.
 */
#if (defined(WIN32) || defined(_WIN32)) && !defined(CURL_STATICLIB)
#if defined(BUILDING_LIBCURL)
#define CURL_EXTERN  __declspec(dllexport)
#else
#define CURL_EXTERN  __declspec(dllimport)
#endif
#else

You can see that by default, every function is declared with the __declspec(dllimport) convention, which add those _imp__ prefixes on symbol names.

So you need to define CURL_STATICLIB in your CMakeLists.txt, like this:

add_definitions(-DCURL_STATICLIB)


来源:https://stackoverflow.com/questions/20461682/linking-project-with-statically-build-curl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!