简体   繁体   中英

Behaviour of extern const char* in C++

In the following example:

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";

When I compile the sources, I got the following errors:

$ 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

I know that in C++ const implies internal linkage, but why there is no an undefined reference error to szVers ?

Update your compiler. With GCC 7.1.0 I can reproduce what you get, but with the newer version I get an error for all three variables:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM