Home > Mobile >  Can static_cast be used in C source code compiled by C compiler?
Can static_cast be used in C source code compiled by C compiler?

Time:04-25

I saw C-library with code that compiled by GCC 11 that do static_cast from C code and it perfectly fine for GCC.

But when I tried to compile this library in VisualStudio (MSVC) I got error: (this library can be compiled by older VS2019(pre-2021 update))

fatal error C1189: #error: STL1003: Unexpected compiler, expected C   compiler.

And only comment about it I saw there https://github.com/ofiwg/libfabric/issues/7041#issuecomment-914839351

Hi! STL maintainer here. We made this change very recently in microsoft/STL#2148 which forbids including standard library headers from C programs.

Maybe im misunderstanding something, very confused.

CodePudding user response:

static_cast is part of the C language, and more importantly it is not part of the C language, so attempts to use static_cast<> should cause a C compiler to emit compile-time errors.

If you've seen it successfully used in "C source code" anyway... one likely explanation is that the "C source" code was being compiled as C source code by a C compiler. Since C is 99% backwards-compatible with C, most C source code can be compiled as C source code and will work, and in that scenario, static_cast could be part of the code and would compile.

Another possibility is that the compiler vendor got a bit sloppy and erroneously allowed a bit of their C -specific functionality to execute even when compiling in the role of a C compiler, but hopefully that's not the case.

  • Related