-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
王艺
committed
May 27, 2024
1 parent
b3b51a3
commit cc75089
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
--- | ||
title: 关于 golang 的条件编译个人实践 | ||
tags: | ||
- 条件编译 | ||
date: 2024-05-27 11:39 | ||
category: | ||
- Golang | ||
--- | ||
|
||
在 Go 中,当你遇到 “build constraints exclude all Go files” 错误时,意味着在某个包中没有符合当前构建条件的文件。 | ||
|
||
## 核心是诊断触发的条件 | ||
|
||
项目中遇到一个服务需要调用 Cplus 开发的库函数实现某些功能,但是仅提供了 Windows 和 Linux 两个平台,导致我们无法在 Darwin 环境运行该服务,算是业务驱动我去更精细化的了解技术了。 | ||
|
||
我期望的条件编译规则如下: | ||
|
||
1. Linux 和 Windows 编译包含库函数的代码; | ||
2. Darwin 不编译; | ||
3. 可以选择是否调用库函数; | ||
|
||
规则 1, 2 可以使用平台条件编译实现: | ||
|
||
```go | ||
// 规则一触发 | ||
//go:build !darwin | ||
|
||
// 规则二触发 | ||
//go:build darwin | ||
``` | ||
|
||
规则 3 需要依赖与 -tags 配置进一步控制编译结果 | ||
|
||
```go | ||
// 符合规则 1, 2 且允许规则 3 时编译 | ||
//go:build !darwin && tag01 | ||
|
||
// 符合规则 2 或不满足规则 3 | ||
//go:build darwin || !tag | ||
``` | ||
|
||
这样配置已经没有问题了,但是仍然提示 “build constraints exclude all Go files” 错误? | ||
|
||
我们可以使用 `go list` 命令来查看哪些文件被包括在内以及哪些被排除: | ||
|
||
`go list -tags ${TAG_NAME} -json ${PACKAGE_NAME}` | ||
|
||
示例输出如下: | ||
|
||
```json | ||
{ | ||
"Dir": "", | ||
"ImportPath": "", | ||
"Name": "bitanswer", | ||
"Files": [], | ||
"GoFiles": [], | ||
"IgnoredGoFiles": [ | ||
"file1.go", | ||
"file2.go" | ||
], | ||
"GoFilesExclude": [ | ||
"file1.go", | ||
"file2.go" | ||
] | ||
} | ||
``` | ||
|
||
## 结论 | ||
|
||
golang 文件夹命名也有条件编译的功能,当文件夹命名符合 filename_os 时,文件中的 `//go:build` 规则会失效。 |