gpt4 book ai didi

c++ - C++ 中 extern const char* 的行为

转载 作者:太空狗 更新时间:2023-10-29 23:12:42 25 4
gpt4 key购买 nike

在下面的例子中:

文件1.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 );
}

文件2.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 的 undefined reference 错误?

最佳答案

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

enter image description here

关于c++ - C++ 中 extern const char* 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44198324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com