Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern const char* const pointer or extern const char array[] cause link error [duplicate]

Tags:

c++

c

ld

here is code:

file1.cc

#include <stdio.h>

const char *pointerString = "pointerString";
const char arrayString[] = "arrayString";
const char* const constpointerString = "constpointerString";

extern void printString();

int main(void)
{
    printString();
    return 0;
}

file2.cc

#include <stdio.h>

extern const char *pointerString;
extern const char arrayString[];
extern const char* const constpointerString;

void printString()
{
    printf("pointerString: %s\n", pointerString);
    printf("arrayString: %s\n", arrayString);
    printf("constpointerString: %s\n", constpointerString);
}

complite command: g++ file1.cc file2.cc -o out error link:

/tmp/cczatCe9.o: In function `printString()':
file2.cc:(.text+0x1f): undefined reference to `arrayString'
file2.cc:(.text+0x30): undefined reference to `constpointerString'
collect2: ld returned 1 exit status

g++ version: 4.6.3(Unbuntu/Linaro 4.6.3-1ubuntu5)

anyone can help??

like image 321
micheal.yxd Avatar asked Apr 29 '26 08:04

micheal.yxd


1 Answers

Put your extern declarations in a header file, and include it in both source files. What's happening is that in file1.cc, arrayString and constpointerString have internal linkage (because that is the default for const objects), and so can't be seen from other translation units.

Alternatively, of course, you can define them:

extern char const arrayString[] = "arrayString";
extern char const* const constpointerString = "constpointerString";

But in general, it is better to use the header.

like image 196
James Kanze Avatar answered May 02 '26 04:05

James Kanze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!