我在使用 Homebrew 的 macOS 上遇到问题,尽管在 include 指令中使用了尖括号,但包含系统标头会导致当前文件的目录中包含同名的头文件。这是一个说明问题的最小示例:
$ cat test.c
#include <time.h>
time_t someTime;
int main(void)
{
return 0;
}
$ cat time.h
$ gcc test.c
test.c:3:1: error: unknown type name 'time_t'
3 | time_t someTime;
| ^~~~~~
test.c:2:1: note: 'time_t' is defined in header '<time.h>'; did you forget to '#include <time.h>'?
1 | #include <time.h>
+++ |+#include <time.h>
2 |
根据 C 编程语言“如果名称包含在 < and > 中,则搜索将遵循实现定义的规则来查找文件。”我的印象是,使用尖括号时不会搜索当前文件的目录,或者至少在搜索系统路径之前不会搜索当前文件的目录。 macOS 上应该是这样还是配置有问题?
使用 -v 选项运行 clang,您将在相关部分所在的位置获得输出
...
#include <...> search starts here:
.
/opt/homebrew/include
/opt/homebrew/include/pango-1.0
...
这意味着确实首先搜索当前目录(.)。解决方案是通过重命名 time.h 来避免名称冲突。