我有可以正确编译和工作的 C 代码,我想在 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;
}
现在,如果我将它放在 .c
文件中并使用 gcc
进行编译,它就可以工作。但是,如果我把它放在一个 .cpp
文件中并用 g++
编译它,我会得到以下错误:
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]
有没有办法表示我没有声明 lambda 函数,只是想填表?
我想保留以下部分:
[4]="seems",
[6]=" it ",
[8]="works",
因为它来自自动生成的文件...
最佳答案
您可以轻松混合 C 和 C++ 代码。
您应该保留要使用 C 编译器 (gcc) 编译的 C 代码,其余代码可以是 C++ 并使用 C++ 编译器 (g++) 编译。然后将所有对象 (.o) 文件链接在一起。
像这样:
文件名:a.c
const char* aTable[12] = {
[4]="seems",
[6]=" it ",
[8]="works",};
文件名:b.cpp
#include <cstdio>
extern "C" const char* aTable[12];
int main(){
printf("%s%s%s", aTable[4],aTable[6],aTable[8]);
return 0;
}
现在编译:
gcc -c a.c -o a.o
g++ -c b.cpp -o b.o
g++ b.o a.o -o all.out
现在运行可执行文件 (all.out),您会发现一切正常。
请注意,对于函数,您需要在 cpp 文件中的声明之前添加 extern "C"
。
关于c++ - C 到 C++ 表内联定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50582946/