CLion生成的EXE文件无法打开,缺失libgcc等DLL问题求助
Hey there, I’ve dealt with this exact issue when using MinGW with CLion, so let’s break down the problem and solutions clearly—no overly technical jargon needed.
Why This Happens
By default, when you compile a C/C++ project in CLion (using MinGW), the linker uses dynamic linking for libraries like libgcc and libstdc++. That means your EXE doesn’t include the code from these libraries directly; instead, it looks for the corresponding DLL files at runtime. If those DLLs aren’t in your system’s PATH or the same folder as the EXE, you get that error.
What -static Does (In Plain English)
The -static flag tells the linker to use static linking instead. Instead of relying on external DLLs, it copies all the necessary code from libgcc and libstdc++ directly into your EXE file. This makes the EXE larger, but it runs independently without needing those DLLs present on the target machine.
Step-by-Step Solutions
Option 1: Static Link the Libraries (Recommended for Distribution)
This is the cleanest fix if you want to share your EXE without extra files. Here’s how to set it up in CLion:
- Open your project’s
CMakeLists.txtfile. - Add the static linking flags to your target. You have two ways to do this:
- Target-specific setup (better practice, only applies to your project):
add_executable(YourProjectName main.cpp) # Replace with your actual target name target_link_libraries(YourProjectName PRIVATE -static -static-libgcc -static-libstdc++) - Global setup (applies to all targets in the project):
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static -static-libgcc -static-libstdc++")
- Target-specific setup (better practice, only applies to your project):
- Click the Reload CMake Project button (the refresh icon in the CMake toolbar) to apply the changes.
- Recompile your project. The new EXE will include all necessary library code and run without missing DLLs.
Option 2: Copy the Missing DLLs to the EXE Folder
If you don’t want to static link (e.g., to keep the EXE size smaller), you can manually copy the DLLs:
- Locate your MinGW installation directory (e.g.,
C:\mingw64\binfor 64-bit MinGW). - Find
libgcc_s_sjlj-1.dllandlibstdc++-6.dllin thebinfolder. - Copy both files into the same directory as your generated EXE.
- Now your EXE should run normally, as it can find the DLLs right next to it.
Quick Notes
- The
-static-libgccand-static-libstdc++flags are more precise than just-static—they only static link the GCC and C++ standard libraries, leaving other system libraries (like Windows APIs) as dynamic links (which is usually what you want). - If you’re using a different compiler toolchain (not MinGW), the steps might vary slightly, but the core idea of static linking vs. copying DLLs still applies.
内容的提问来源于stack exchange,提问作者Szymon Gajdzica

