如何编写指定平台生效的.gitignore?Qt跨平台项目语法咨询
Great question! Let’s break this down clearly for your cross-platform Qt project. First off: Git’s .gitignore doesn’t support a block syntax like macx{ ... } win{ ... } out of the box. But there are two reliable, straightforward ways to set up OS-specific ignore rules that work perfectly.
Method 1: Conditional Includes in the Main .gitignore (Git 2.13+)
Git added support for OS-based conditional ignore rules in version 2.13, which is the cleanest approach if your team uses modern Git versions. Here’s how to structure your .gitignore:
# Shared Qt/compile rules (applied to all platforms) *.o *.obj *.exe *.dll *.so *.dylib qmake.cache qmake.stash Makefile build/ # Mac-specific ignore rules if:os=darwin .DS_Store .AppleDouble .LSOverride Icon? ._* *.dSYM/ # Windows-specific ignore rules if:os=windows Thumbs.db Thumbs.db:encryptable *.bak *.tmp *.user *.suo *.vcxproj.user
- Check your Git version with
git --versionto ensure it’s 2.13 or newer. if:os=darwintargets macOS, whileif:os=windowstargets Windows. Git automatically applies the rules under each condition based on the current operating system.
Method 2: Separate Platform-Specific .gitignore Files
If you need to support older Git versions, or prefer to keep OS rules completely separated, use Git’s core.excludesfile configuration to load platform-specific ignore files:
Create two local ignore files in your project root:
.gitignore_mac(add all Mac-only rules here).gitignore_win(add all Windows-only rules here)
On each developer’s machine, run the matching command to set the local exclude file:
- Mac:
git config core.excludesfile .gitignore_mac - Windows:
git config core.excludesfile .gitignore_win
- Mac:
⚠️ Note: Don’t commit .gitignore_mac or .gitignore_win to your repository—these are local configuration files. Keep your main .gitignore for shared, cross-platform rules.
Bonus Qt Project Tip
Since you’re working with Qt, make sure to add cross-platform Qt-generated files (like qmake.cache, build/ directories, and platform binaries) to your main .gitignore—this keeps shared cruft ignored everywhere, while only OS-specific junk is handled by the conditional rules.
内容的提问来源于stack exchange,提问作者Princekin

