C to C++ table inline definition

  • A+
Category:Languages

I have code in C that compiles and works correctly and I would like to use similar code in C++:

static const char* aTable[12] = {     [4]="seems",     [6]=" it  ", [8]="works",};  int main(){     printf("%s%s%s", aTable[4],aTable[6],aTable[8]);      return 0; } 

Now if I put it in a .c file and compiles with gcc it works. But, if I put it in a .cpp file and compile it with g++, I get the following errors:

test_cpp.cpp:5:3: error: expected identifier before numeric constant test_cpp.cpp:5:4: error: type '<lambda>' with no linkage used to declare function 'void<lambda>::operator()() const' with linkage [-fpermissive]  test_cpp.cpp: In lambda function: test_cpp.cpp:5:5: error: expected '{' before '=' token  test_cpp.cpp: At global scope: test_cpp.cpp:5:5: warning: lambda expressions only available with     -std=c++0x or -std=gnu++0x [enabled by default]  test_cpp.cpp:5:6: error: no match for 'operator=' in '{} = "seems"' test_cpp.cpp:5:6: note: candidate is: test_cpp.cpp:5:4: note: <lambda()>&<lambda()>::operator=(const<lambda()>&)  test_cpp.cpp:5:4: note:   no known conversion for argument 1 from 'const char [6]' to 'const<lambda()>&'  test_cpp.cpp:6:3: error: expected identifier before numeric constant test_cpp.cpp:6:4: error: type '<lambda>' with no linkage used to declare function 'void<lambda>::operator()() const' with linkage [-fpermissive] 

Is there a way to express that I am not declaring a lambda function, just trying to fill a table?

I would like to keep the following part :

[4]="seems", [6]=" it  ", [8]="works", 

because it comes from an autogenerated file...


You can mix C and C++ code easily.

You should keep the C code to be compiled with C compiler, rest of the code can be C++ and be compiled with g++.

like this:

file name: a.c

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

file name: b.cpp

#include <cstdio> extern 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.o g++ -c b.cpp -o b.o g++ 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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: