extern const char *在C ++中的行为

时间:2017-05-26 09:39:39

标签: c++ string linker const extern

在以下示例中:

file1.c中:

#include <stdlib.h>
#include <stdio.h>

extern const char* szVers;
extern const int iTest;
extern const char cText[];

int main( int argc, char** argv )
{
    printf( "Result = %s - %d - %c\n", szVers, iTest, cText[0] );
    return ( 0 );
}

file2.c中

const char* szVers = "Version 1.0";
const int iTest = 6;
const char cText[] = "ABCD";

编译源代码时,出现以下错误:

$ g++ -o test file1.c file2.c
/tmp/cctVd57Y.o: In function `main':
file1.c:(.text+0x12): undefined reference to `cText'
file1.c:(.text+0x1b): undefined reference to `iTest'
collect2: ld returned 1 exit status

我知道在C ++中 const 意味着内部链接,但为什么szVers没有未定义的引用错误?

1 个答案:

答案 0 :(得分:0)

更新您的编译器。使用GCC 7.1.0,我可以重现你得到的东西,但是对于新版本,我得到了所有三个变量的错误:

enter image description here