简体   繁体   English

Windows互斥锁的gcc编译错误

[英]gcc compile error for windows mutex

Why does the compile give me error: initializer element is not constant for a simple creation of a mutex HANDLE ghMutex = CreateMutex( NULL, FALSE, NULL); 为什么编译会给我带来error: initializer element is not constant对于简单创建互斥锁, error: initializer element is not constant HANDLE ghMutex = CreateMutex( NULL, FALSE, NULL);

I've tried searching but I am totally stumped. 我已经尝试过搜索,但是我完全陷入了困境。 No matter what I do it won't compile.I even tried breaking it up: 无论我做什么,它都不会编译,我什至试图将其分解:

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

And the compile complain: 并且编译抱怨:

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);

I think there is something wrong with my syntax I just don't know what. 我认为我的语法有问题,我只是不知道是什么。

For variables outside of a function, in C, they are part of the .data part of the executable, wherein memory is allocated at compile time. 对于函数外部的变量,在C中,它们是可执行文件的.data部分的一部分,其中在编译时分配内存。 Without a constant (which the return variable of CreateMutex is not), there is no way to know how much memory to allocate. 没有常量( CreateMutex的返回变量不是常量),就无法知道要分配多少内存。

To circumvent this, the compiler throws an error, so that you have to put the initialisation in a function so that memory is allocated dynamically at run-time. 为了避免这种情况,编译器会引发错误,因此您必须将初始化放入函数中,以便在运行时动态分配内存。

This error isn't specific to Mutexes either. 此错误也不特定于互斥体。 The following code would also throw the error: 以下代码也将引发错误:

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

If you're just interested in seeing how would would get around the error, then you could do something like this: 如果您只是想知道如何解决该错误,则可以执行以下操作:

#include <windows.h>    

HANDLE ghMutex;

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

This works because ghMutex is being allocated at run-time, because it is in a function. 之所以ghMutex是因为ghMutex在运行时分配,因为它在函数中。 As OP stated in a comment: "The problem was [that ghMutex was] outside the function." 正如OP在评论中指出的那样:“问题出在ghMutex在函数之外。”

Or if you'd like a more in-depth view, the documentation also displays this: https://msdn.microsoft.com/en-gb/library/windows/desktop/ms686927(v=vs.85).aspx 或者,如果您想要更深入的了解,文档也会显示以下内容: https : //msdn.microsoft.com/zh-CN/library/windows/desktop/ms686927(v=vs.85).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM