我想完成一个c ++可执行文件,该文件可以链接到我自己的另一个c ++库,而没有libstdc ++依赖性。我可以毫不费力地创建没有库的c ++可执行文件。但是,一旦我将其链接到我的库,该可执行文件便立即具有libstdc ++依赖关系。不需要将libstdc ++ 6.dll(或任何其他.dll)复制到Windows。
我正在使用最新的mingw64(x86_64-w64-mingw32-gcc(GCC)4.9.3)在Linux(Centos 7)上构建,并交叉编译到Windows。在MSYS2 / MingW上构建具有相同的不良结果。
(顺便说一句,我同时安装了libstdc ++-static和glibc-static)
在此示例中,两行标记为“ COMMENT ME OUT”:一行在hello_c / main.cpp中,另一行在hello_c / CMakeLists.txt中。如果将其注释掉,则将删除对hello_lib库的引用;该项目将在没有libstdc ++依赖的情况下在Windows 10上生成并执行。如果取消注释这两行,则会链接到hello_lib库中的函数;该项目可以构建,但是由于libstdc ++依赖关系而无法在Windows 10上执行。 (注意:在powershell中,它无提示地失败,在老式的dos / cmd框中显示错误消息。)
该示例具有以下结构:
hello_lib/library.cpp
hello_lib/library.h
hello_lib/CMakeLists.txt
hello_c/main.cpp
hello_c/CMakeLists.xt
buildme.sh
toolchain.cmake
## hello_lib/library.h:
int hello();
// hello_lib/library.cpp:
#include "library.h"
int hello() {
return 666;
}
## hello_lib CMakeLists.txt:
cmake_minimum_required(VERSION 3.13)
project(hello_lib)
set(CMAKE_CXX_STANDARD 11)
if(MINGW)
# Including these flags on Linux on Linux build = "Missing ELF Interpreter" error
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static -static-libgcc -static-libstdc++")
endif()
add_library(hello_lib STATIC library.cpp)
## hello_c/main.cpp:
#include <iostream>
#include "../hello_lib/library.h"
int main() {
std::cout << "Hello, world" << std::endl;
//COMMENT ME OUT:
printf("x = %d\n", hello());
return 0;
}
## hello_c CMakeLists.txt:
cmake_minimum_required(VERSION 3.13)
project(hello_c)
set(CMAKE_CXX_STANDARD 11)
if(MINGW)
# Including these flags on Linux on Linux build = "Missing ELF Interpreter" error
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static -static-libgcc -static-libstdc++")
endif()
link_directories(../hello_lib/cmake-build-debug)
add_executable(hello_c main.cpp)
# COMMENT ME OUT:
target_link_libraries(hello_c -static-libgcc -static-libstdc++ libhello_lib.a)
## buildme.sh:
#!/bin/bash
set -e
for i in hello_lib hello_c
do
rm -rf $i/cmake-build-debug
mkdir $i/cmake-build-debug
pushd $i/cmake-build-debug
# For building Win64 on Linux (with MinW64):
cmake .. -DCMAKE_TOOLCHAIN_FILE="../toolchain.cmake" -DCMAKE_BUILD_TYPE=Debug
# For building Win64 on Win64/MSYS2/MinW64:
#cmake .. -G "MSYS Makefiles" -DCMAKE_BUILD_TYPE=Debug
# For building Linux on Linux
#cmake .. -DCMAKE_BUILD_TYPE=Debug
make
popd
done
## toolchain.cmake:
set(CMAKE_SYSTEM_NAME Windows)
set(TOOLCHAIN_PREFIX x86_64-w64-mingw32)
set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc)
set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++)
set(CMAKE_RC_COMPILER ${TOOLCHAIN_PREFIX}-windres)
set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX})
在Linux上的MingW64和Windows 10上的MingW64 / MSYS2上,当我链接到“ hello_lib”库时,都会得到libstdc ++依赖项。在这两种情况下,如果我注释掉对hello_lib的引用,都会消除libstdc ++依赖性。