Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying -std when compiling both C and C++ code

Tags:

Suppose I have a codebase consisting of both C and C++ code, like so:

t.c:

int derp(void)
{
    return 42;
}

t.cpp:

#include <iostream>

extern "C" int derp(void);

int main(void)
{
    std::cout << derp() << std::endl;
    return 0;
}

With clang(++), I can both compile them in one go, like so:

clang++ -o t -xc++ t.cpp -xc t.c

However, if I now want to use non-standard features from e.g. gnu++14 and invoke the compiler like so:

clang++ -o t -xc++ -std=gnu++14 t.cpp -xc t.c

I am greeted with an error:

error: invalid argument '-std=gnu++14' not allowed with 'C/ObjC'

Unlike -x, -std does not seem to work based on a file level, but to be a global option, because adding -std=c11 like so:

clang++ -o t -xc++ -std=gnu++14 t.cpp -xc -std=c11 t.c

Simply gives me the "inverse" error, so to speak:

error: invalid argument '-std=c11' not allowed with 'C++/ObjC++'

And I know that I can compile each source file into an .o file separately and link them together afterwards (and yes, I'm automating the whole process anyway), but I cannot help but think that compiling with different standards per language should be possible. After all, clang supports compiling files in different languages together, and when doing that it would need separate values for the standards already, or not?

So, is there a way with clang(++) to manually specify standards when compiling both C and C++ code?

like image 638
Siguza Avatar asked Jul 07 '18 00:07

Siguza


People also ask

Can we use same compiler for C and C++?

Any C compiler that is compatible with the Oracle Developer Studio C compiler is also compatible with the Oracle Developer Studio C++ compiler. The C runtime library used by your C compiler must also be compatible with the C++ compiler.

Can you include .C files in C?

You can properly include . C or . CPP files into other source files.


1 Answers

You can compile C, and you can compile C++.

You cannot compile as both C and C++.

Compile your C source files with C-appropriate flags.

Then compile your C++ source files with C++-appropriate flags (e.g. -std=gnu14).

Then link the results together to get an executable.

clang   -o a.o t.c
clang++ -o b.o t.cpp -std=gnu++14
clang++ -o t   a.o b.o

You cannot use the shorthand you've attempted to do both at once. It is designed as a shortcut for when all the flags and all the whatevers are the same. That's despite the magic of -x which sort of gets you close-ish.

like image 188
Lightness Races in Orbit Avatar answered Sep 22 '22 18:09

Lightness Races in Orbit