如何通过SConstruct(mingw工具)在Linux环境自动编译Windows平台.dll文件
I’ve run into similar cross-compiling quirks with SCons before, so let’s fix this step by step. The core issue is that SCons relies on the target platform context to determine valid shared library suffixes—when you don’t explicitly specify you’re targeting Windows, it defaults to your host (Linux) and expects .so files. Here’s how to configure separate environments for both platforms and build both libraries in one go:
Final Working SConstruct Code
import os cpp_source = 'theone.cpp' # 1. Configure environment for Windows cross-compilation (MinGW) win_env = Environment( tools=['mingw'], platform='win32', # Tells SCons we're targeting Windows CXX='x86_64-w64-mingw32-g++' ) # Build Windows DLL (SCons will automatically append .dll) win_dll = win_env.SharedLibrary('foo', cpp_source) # 2. Configure environment for native Linux compilation linux_env = DefaultEnvironment() # Build Linux shared library (SCons appends .so by default) linux_so = linux_env.SharedLibrary('foo', cpp_source) # Set both targets as default so `scons` builds both Default([win_dll, linux_so])
Why This Works
Fixing the DLL Build Error
Your earlier attempt failed because you manually added .dll to the target name, but SCons still thought you were targeting Linux (since platform wasn’t set). By explicitly setting platform='win32', SCons switches to Windows-specific rules:
- It automatically uses
.dllas the shared library suffix, so you only need to specify the base namefoo - It adjusts linker flags appropriately for Windows DLLs (like generating the
libfoo.aimport library)
Separate Environments
We create two distinct environments to keep cross-compilation and native build settings isolated:
- The
win_envuses the MinGW toolchain and follows Windows platform rules - The
linux_envuses your system’s default GCC compiler and Linux platform rules
Verification
After running scons, you’ll get:
libfoo.so: Native Linux shared librarylibfoo.dll: Windows 64-bit DLL (along withlibfoo.a, the import library needed for linking on Windows)
You can test the DLL on Windows 10 as you did before—it should work exactly like your manually compiled version.
Prerequisite Check
Make sure you have the MinGW-w64 toolchain installed on Ubuntu:
sudo apt update && sudo apt install gcc-mingw-w64-x86-64
内容的提问来源于stack exchange,提问作者Beyto A.

