2

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


5
  • try building common.cpp
    – M.M
    Mar 26, 2020 at 10:17
  • 1
    To be honest I'm kind of surprised it compiles, because the type of pallete is incomplete without specifying a size. Mar 26, 2020 at 10:20
  • 1
    As for the linker error you get, how do you build your application? Are you building together with common.cpp, or linking with the object file created from common.cpp? Mar 26, 2020 at 10:21
  • 1
    anyway avoid declaring extern global variables and global variables in general. pass them by parameter instead.
    – AndersK
    Mar 26, 2020 at 10:22
  • 1
    On a totally unrelated note, please don't use char for small integers, just use plain int (or in your case unsigned instead of unsigned char). Once you get the program to build you will notice that it doesn't seem to output anything for pallete[0], because the operator<< function will treat it as a character and not an intege. If you want to print the integer value you need to cast it (e.g. static_cast<unsigned>(pallete[0])). If you're required to use unsigned char then please use uint8_t instead (to make it semantically clearer that it's not character data). Mar 26, 2020 at 10:26

3 Answers 3

2

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;
0
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.

-1

extern can be added:

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

than translation unit treats it as external despite being const...

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.