windows mutex 的 gcc 编译错误

gcc compile error for windows mutex

为什么编译会给我 error: initializer element is not constant 一个简单的互斥体创建 HANDLE ghMutex = CreateMutex( NULL, FALSE, NULL);

我试过搜索,但完全被难住了。无论我做什么它都不会 compile.I 甚至尝试分解它:

HANDLE ghMutex;
ghMutex = CreateMutex( NULL, FALSE, NULL);

编译抱怨:

test.c:90:1: error: conflicting types for 'ghMutex'
test.c:89:8: note: previous declaration of 'ghMutex' was here
 HANDLE ghMutex;
        ^
test.c:90:1: error: initializer element is not constant
 ghMutex = CreateMutex( NULL, FALSE, NULL);

我认为我的语法有问题我只是不知道是什么。

对于函数外部的变量,在 C 中,它们是可执行文件 .data 部分的一部分,其中内存是在编译时分配的。没有常量(CreateMutex 的 return 变量不是),就无法知道要分配多少内存。

为了避免这种情况,编译器会抛出错误,因此您必须将初始化放在一个函数中,以便在 运行 时动态分配内存。

这个错误也不是互斥量特有的。以下代码也会引发错误:

int x = 3;
int y = 5;
int z = x*y;
int main(void)
{
    return 0;
}

如果您只是想知道如何解决该错误,那么您可以这样做:

#include <windows.h>    

HANDLE ghMutex;

int main(void)
{
    ghMutex = CreateMutex(NULL, FALSE, NULL);
    CloseHandle(ghMutex);
    return 0;
}

这是有效的,因为 ghMutex 是在 运行 时间分配的,因为它在一个函数中。正如 OP 在评论中所述:"The problem was [that ghMutex was] outside the function."

或者,如果您想要更深入的视图,文档还会显示:https://msdn.microsoft.com/en-gb/library/windows/desktop/ms686927(v=vs.85).aspx