extern array goes undefined reference error, but works well for int

Viewed 500

compile error : [build] main.cpp:8: undefined reference to `pallete'

example code: common.cpp

const unsigned char pallete[] = {0, 60, 100, 119};
int a = 1;

main.cpp

#include <iostream>

extern const unsigned char pallete[];
extern int a;

int main() {
    std::cout << a << std::endl;
    std::cout << pallete[0] << std::endl;
    return 0;
}


2 Answers

You have to declare pallete extern in common.cpp. Right now main.cpp knows that it should "look for" pallete in separate file but common.cpp treats it as local due to being const as it says here https://en.cppreference.com/w/cpp/language/cv#Notes

Notes

The const qualifier used on a declaration of a non-local non-volatile non-template (since C++14)non-inline (since C++17) variable that is not declared extern gives it internal linkage. This is different from C where const file scope variables have external linkage.

extern const unsigned char pallete[] = {0, 60, 100, 119};
int a = 1;

Most likely your compiler does what mine is warning about: Warnung: variable 'pallete' is not needed and will not be emitted

If you add your extern statement also in the common.cpp it should work.

If you declare something extern you should always do it in some header which is included by everyone who wants to use the variable.

Related