Problem with language detection and -std flag

Trying to use zig as drop-in compiler replacement in a Conan/CMake based build system. I’m now stuck in the build stage of the lua component which forces C++ compilation for C files using set_source_files_properties in the CMakeLists. This clashes with zig’s extension-based language detection. The source file properties in CMake enforce usage of CXX compiler (which is configured to zig c++) and CMake appends the -std=c++17 flag, but the source files passed via -c have .c extension. This results in the following errors:

error: invalid argument '-std=c++17' not allowed with 'C'

I need the C files to be compiled with C++ (because of name mangling and exception usage requirements) and I cannot remove the -std flag from the CXXFLAGS, because it is required for C++ compilation.

To solve this problem zig should either ignore the -std=c++xx flags in combination with C input files, provide a way to globally override the language of the input files (-x needs proper positioning which is difficult to manage across the many build system layers), allow to globally disable extension-based detection or provide a way to suppress the invalid argument error.

Hmm, interesting, I would expect that at least this would work to force C++ mode for C files:

zig c++ -xc++ hello.c -o hello

…but this also compiles as C…

(it’s how it works in Clang):

clang++ -xc++ hello.c -o hello

…also interesting: omitting the -xc++ creates a deprecation warning in clang:

clang++ hello.c -o hello

clang++: warning: treating ‘c’ input as ‘c++’ when in C++ mode, this behavior is deprecated [-Wdeprecated]

(this is the test code I’ve been using):

#include <stdio.h>

int main() {
    #if defined(__cplusplus)
        printf("This is C++\n");
    #else
        printf("This is C\n");
    #endif
    return 0;
}

What is the purpose of the -xc++ parameter then? And how is that problem handled in clang-based projects? I mean it should be possible to build lua with clang, so what is the difference?

-xc++ is just a manual override for the file-extension based language detection, e.g. even clang++ wants to compile .c files as C without that override (but apparently that behaviour is deprecated).

In reverse, clang (without the ++) compiles .cpp files as C++ but can be forced with -xc to compile as C.

Totally makes sense IMHO, except that zig cc and zig c++ don’t seem to support the -x override flag. The fact that zig c++ compiles .c files as C could be both a bug or an intended features though (but if it is the latter there really needs to be an override similar to clang’s -x flag)

1 Like

Ah thanks for the clarification. I read it as “-xc++ does not work in clang either”.