C to C++ table inline definition C to C++ table inline definition c c

C to C++ table inline definition


You can mix C and C++ code easily.

You should keep the C code to be compiled with C compiler (gcc), rest of the code can be C++ and be compiled with C++ compiler (g++). then link all object (.o) files together.

like this:

file name: a.c

const char* aTable[12] = {    [4]="seems",    [6]=" it  ",[8]="works",};

file name: b.cpp

#include <cstdio>extern "C" const char* aTable[12];   int main(){    printf("%s%s%s", aTable[4],aTable[6],aTable[8]);     return 0;}

Now compile:

gcc -c a.c -o a.og++ -c b.cpp -o b.og++ b.o a.o -o all.out

Now run the executable (all.out) and you'll see that everything will work.

Just note that for functions you'll need to add extern "C" before the declaration in the cpp file.


There's no way to do this. C++ never adopted this particular C syntax.

In your case, since the table is auto-generated, I would just put it in a C file. As long as it's not marked static, it can be accessed from C++ code without problems.


[4]= is a designated initializer, one of the C features not supported by C++.

Here is a list that tries to list which C99 features that are supported by C++17. Scroll down to the bottom to see which ones that are not supported.

It is important to realize that C++ is by no means a superset of C.