source

C에서 C++ 테이블 인라인 정의

ittop 2023. 9. 9. 10:14
반응형

C에서 C++ 테이블 인라인 정의

저는 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;
}

이제 제가 이걸 A에 넣으면.c줄로 묶어서 정리하는gcc그건 효과가 있다.하지만, 제가 이걸 A에..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]

람다 함수를 선언하는 것이 아니라 테이블을 채우려는 것이라고 표현할 방법이 있습니까?

저는 다음 부분을 유지하고 싶습니다.

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

자동 생성된 파일에서 나왔기 때문에...

C와 C++ 코드를 쉽게 섞을 수 있습니다.

C 코드는 C 컴파일러(gcc)로 컴파일하고 나머지 코드는 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)을 실행하면 모든 것이 작동합니다.

기능의 경우 추가해야 한다는 점만 유의하십시오.extern "C"cpp 파일의 선언 전에.

이럴 방법이 없습니다.C++는 이 특정한 C 구문을 채택한 적이 없습니다.

당신의 경우 테이블이 자동 생성되기 때문에 그냥 C 파일에 넣겠습니다.표시되지 않은 한static, C++ 코드에서 문제없이 접근할 수 있습니다.

[4]=은 C++에서 지원하지 않는 C 기능 중 하나인 지정 이니셜라이저입니다.

다음은 C++17에서 지원하는 C99 기능 목록입니다.아래쪽으로 스크롤하여 지원되지 않는 것을 확인합니다.

C++가 결코 C의 상위 집합이 아니라는 것을 깨닫는 것이 중요합니다.

지정된 이니셜라이저는 이미 언급된 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;

코드를 테스트하지 않았으니 버그를 발견하면 자유롭게 고쳐주세요...

위와 같이 C++에서는 이러한 유형의 초기화가 지원되지 않지만 람다 함수를 사용하여 초기화할 수 있습니다.static array<const char*, 12>다음과 같이:

#include <array>
#include <cstdio>

static const std::array<const char*, 6> aTable = []() {
    std::array<const char*, 6> table;
    table[0] = "Hello";
    table[3] = ", ";
    table[5] = "world!";
    return std::move(table);
}();

int main() {
    printf("%s%s%s\n", aTable[0], aTable[3], aTable[5]);
    return 0;
}

Demo on coliru

주목할 점은, 해당 컴파일러가 여기서 RVO를 수행하고 초기화는 제자리에서 수행된다는 것입니다.이 어셈블리는 g++-5.4.0에 의해 생성됩니다.

<_GLOBAL__sub_I_main>:
movq   $0x40064c,0x200bc5(%rip)        # 601060 <_ZL6aTable>
movq   $0x400652,0x200bd2(%rip)        # 601078 <_ZL6aTable+0x18>
movq   $0x400655,0x200bd7(%rip)        # 601088 <_ZL6aTable+0x28>
retq   

언급URL : https://stackoverflow.com/questions/50582946/c-to-c-table-inline-definition

반응형