我在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;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我把它放在一个.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]
Run Code Online (Sandbox Code Playgroud)
有没有办法表达我没有声明一个lambda函数,只是想填充一个表?
我想保留以下部分:
[4]="seems",
[6]=" it ",
[8]="works",
Run Code Online (Sandbox Code Playgroud)
因为它来自一个自动生成的文件......
SHR*_*SHR 28
您可以轻松地混合使用C和C++代码.
你应该保持C代码用C编译器(gcc)编译,其余的代码可以是C++,并用C++编译器(g ++)编译.然后将所有对象(.o)文件链接在一起.
像这样:
文件名:ac
const char* aTable[12] = {
[4]="seems",
[6]=" it ",
[8]="works",};
Run Code Online (Sandbox Code Playgroud)
文件名:b.cpp
#include <cstdio>
extern "C" const char* aTable[12];
int main(){
printf("%s%s%s", aTable[4],aTable[6],aTable[8]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在编译:
gcc -c a.c -o a.o
g++ -c b.cpp -o b.o
g++ b.o a.o -o all.out
Run Code Online (Sandbox Code Playgroud)
现在运行可执行文件(all.out),你会发现一切都会正常工作.
请注意,对于函数,您需要extern "C"
在cpp文件中的声明之前添加.
已经提到的C++不支持指定的初始化程序 - 如果你坚持使用C++,你可以编写一个带有构造函数的包装类:
class Table
{
std::array<char const*, 12> data;
public:
Table()
{
data[4] = "seems";
data[6] = " it ";
data[8] = "works";
}
char const* operator[](unsigned int index) const
{
return data[index];
}
} aTable;
Run Code Online (Sandbox Code Playgroud)
没有测试代码,所以如果你发现了一个bug,请随意修复它...