c++ - C 到 C++ 表内联定义

标签 c++ c gcc g++

我有可以正确编译和工作的 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/

相关文章:

c - 了解 gdb 中的这种不稳定行为

c++ - flens lapack : GNU GCC Version 4. 7 或更高要求!我的 mac 有

c++ - 使用 libarchive 读取目录

c - 为什么在Eclipse中的printf之前执行scanf?

c++ - 有没有办法检查 istream 是否以二进制模式打开?

c - _mm256_shuffle_ps 是如何工作的?

c - 使用 unsigned long long int 的函数的结果不正确

c - 过程声明和定义不匹配

c++ - Windows 编辑启动应用程序/C++

c++ - 从标准输入 C++ 读取数百万整数的最快方法?