如何配置qmake的.pro文件以生成含自定义预构建步骤的Makefile?
Got it, let's walk through how to set up a custom pre-build step in your .pro file so qmake generates the exact Makefile structure you want—where the first target depends on both pre-build and release, with custom actions under the pre-build rule.
Step 1: Define Your Pre-Build Target
First, create a custom target for your pre-build actions. This tells qmake what commands to run when the pre-build target is triggered:
# Define the pre-build target and its commands pre-build.target = pre-build pre-build.commands = echo "Running pre-build steps..." && \ # Add your actual operations here—examples below: cp ./config.template ./src/config.h && \ python ./scripts/generate_resources.py
- Use
&&to chain multiple commands, or line breaks with\for readability. - Replace the example commands with whatever you need (file copying, code generation, environment setup, etc.).
Step 2: Register the Target with qmake
Next, add your pre-build target to qmake's list of extra targets. This ensures qmake includes the target rule in the generated Makefile:
QMAKE_EXTRA_TARGETS += pre-build
Step 3: Adjust the Default first Target Dependencies
By default, qmake's generated Makefile sets first: release (or first: debug depending on your build mode). To modify this to first: pre-build release, redefine the first target's dependencies:
# Override the first target to depend on pre-build first, then release first.depends = pre-build release first.commands = @true # Empty command—first just triggers its dependencies
The @true is a no-op command; since first only exists to trigger its dependent targets, we don't need it to execute any actual logic.
Full Example .pro File Snippet
Putting it all together, here's how your .pro file might look:
QT += core gui widgets TARGET = MyQtApp TEMPLATE = app # Pre-build setup pre-build.target = pre-build pre-build.commands = echo "Starting pre-build tasks..." && \ mkdir -p ./build/assets && \ cp ./assets/* ./build/assets/ QMAKE_EXTRA_TARGETS += pre-build # Modify default target dependencies first.depends = pre-build release first.commands = @true # Rest of your .pro file content SOURCES += main.cpp \ mainwindow.cpp HEADERS += mainwindow.h
What Happens When You Run qmake?
After running qmake, the generated Makefile will have:
- A
pre-buildrule with your custom commands - The
firsttarget defined asfirst: pre-build release
Now when you run make, it will execute all your pre-build commands first, then proceed with the standard release build process.
Bonus: Target Debug and Release Builds
If you want the pre-build step to run for both debug and release modes, adjust the dependencies to cover both targets:
first.depends = pre-build release.depends = pre-build debug.depends = pre-build
This way, no matter if you build debug or release, the pre-build steps run first.
内容的提问来源于stack exchange,提问作者Konstantin Utkin

