为什么对于gcc来说,"UNIX"和"unix"宏不是一回事?

Why for gcc 'UNIX' and 'unix' macros are not the same thing?

本文关键字:unix 一回事 UNIX gcc 来说 为什么      更新时间:2023-10-16

我在Ubuntu Mate中遇到了一个奇怪的问题。

我需要编写一个使用第三方 C 库的 golang 程序,但我遇到了一个问题。

当我尝试在此代码中连接第三方库时:

package main
// #cgo CFLAGS: -I /opt/cprocsp/include/interfaces/
// #cgo CFLAGS: -I /opt/cprocsp/include/
// #cgo CFLAGS: -I /opt/cprocsp/include/cpcsp/
// #include <stddef.h>
// #include "wincspc.h"
// #include "wincspc_int.h"
import "C"
func main() {
var CSPConfig C.CPC_CONFIG
C.CPCGetDefaultConfig(&CSPConfig, nil)
CSPConfig.logConfig.name = string(C.MODNAME)
}

我收到编译错误:

In file included from /opt/cprocsp/include/cpcsp/wincspc.h:28:0,
from ./gost.go:7:
/opt/cprocsp/include/cpcsp/WinCryptEx.h:35:10: fatal error: wincrypt.h: No such file or directory
#include <wincrypt.h>
^~~~~~~~~~~~
compilation terminated.

我不知道这个错误是什么意思。接下来,我决定打开WinCryptEx.h,我在那里找到了这些行:

#if defined UNIX || defined CSP_LITE
#include "CSP_WinCrypt.h"
#else // UNIX
#include <wincrypt.h>
#endif // UNIX

所以我意识到编译器运行 else 语句(但我希望它运行 if 语句,因为我的操作系统是 Linux(。为了确认问题,我决定编写一个 C 示例。

#if defined UNIX
#include "CSP_WinCrypt.h"
#else 
#include <wincrypt.h>
#endif 
int main()
{
printf("Hello world");
}

当我尝试运行此示例时,出现相同的错误。 但后来我决定尝试运行下一个代码:

#if defined unix
#include "CSP_WinCrypt.h"
#else 
#include <wincrypt.h>
#endif 
int main()
{
printf("Hello world");
}

而且它工作正常!!编译器根据需要运行 if 语句。 我不明白为什么。

我无法更改第三方库。所以我需要编译器与"UNIX"宏正确工作。

有人有解决方案吗?提前谢谢。

这个对流行的互联网搜索引擎的查询只带来了一个与"unix"一词匹配的页面,在适当的上下文中:它是关于系统特定宏的页面。

该页面暗示了两件事:

  • GCC 不保证定义了UNIX宏。

  • unix宏被描述为"通用",但没有任何东西 说明它必须存在的事实:

    但是,历史上特定于系统的宏的名称没有特殊的前缀;例如,在Unix系统上找到定义的unix是很常见的。对于所有这些宏,GCC 提供了一个并行宏,并在开头和结尾添加两个下划线。如果定义了unix__unix__也将定义。

无论哪种情况,C 中的标识符都区分大小写,其预处理器处理的符号也是如此,因此unixUNIX是两个不相关的符号。

在您的情况下,我应该反转逻辑并测试 Windows,而不是相反。
在那里,符号_WIN32应由MinGW和MSVC定义。