简体   繁体   中英

Macro error in C99 and MS Visual Studio 2015

we have problems compiling our GCC C99 code with MSVS 2015. The problematic line seems to be a macro expansion, the problem occurs in this line:

const UA_QualifiedName dateName = UA_QUALIFIEDNAME(1, "current time");

The error is something like this

IntelliSense a value of type âUA_Stringâ cannot be used to initialize an entity of type âUA_Int32â.

where macros are as follows:

#define UA_QUALIFIEDNAME(NS_INDEX, CHARS) (const UA_QualifiedName) { \
                        .namespaceIndex = NS_INDEX, .name = UA_STRING(CHARS) }
#define UA_STRING(CHARS) (UA_String) {strlen(CHARS), (UA_Byte*)CHARS }

and structs are

typedef struct {
    UA_Int32 length;
    UA_Byte *data;
} UA_String;

as well as

typedef struct {
    UA_UInt16 namespaceIndex;
    UA_String name;
} UA_QualifiedName;    

It is valid C code as far as I can see it. Does anyone have an idea how we can workaround it for MSVS?

PS: apparently it seems to be the cast to UA_String in the second macro. However, removing it breaks the code for gcc and clang

C99 introduced support for a feature known as compound literals, which manifests as the cast to UA_String in the second macro . That isn't actually a cast. It's an initialisation, and use of an anonymous object. You're right, though... It's been valid C, for at least fifteen years now.

Unfortunately, as you have realised the hard way, MSVS doesn't fully support C99. That's right, there's perfectly valid, portable and compliant C code that was written fifteen years ago and won't compile using MSVS .

Microsoft claims support in the documentation (as they have introduced some C99ish functions). They haven't introduced any of the core language additions, such as compound literals , however. In fact, even parts of the library are broken in fundamental ways; printf and scanf need serious updates. MSVS hates C programmers :(

You might have some success compiling C99 code in MSVS by Getting Started with the LLVM System using Microsoft Visual Studio ...

Alternatively, if you must use Microsoft's compiler in spite of their lack of care about your code, the fix is simple enough... Just don't use compound literals .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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