C++ extern const link error

In C++, I tried to reference a constant in flash defined in another file using this declaration:

extern const int count;

In another C++ file I had the definition:

const int count = 1;

(The original test case had more to it, but I boiled it down to this simple scenario.)

The linker gives the error "undefined reference to 'count'".  I am using ARM GCC 9.3.1 on a Cortex-M0+ MCU.

I found if I took off the "const" in both places, thus moving it from flash to RAM, there was no problem.  I also eventually figured out that it all linked (and lived in flash) if I added 'extern "C"' to both.  This is an adequate work-around, but I'd like to know what the problem is.  Is it a bug?  Is there something missing from my declarations?

  • I took off the "const" in both places, thus moving it from flash to RAM

    This is one of those places where C++ differs from C.

    In 'C',

    const int count = 1;

    definitely creates an object in memory.

    But in C++, it doesn't (necessarily); in C++, it could be just like a #define (but with type & scope).

  • Is there something missing from my declarations?

    No, there is nothing missing from your declarations.  What you need to change is your definition.

    "extern const int count = 1" should "fix" the issue you are seeing.

    In C++, const global variable definitions have internal linkage by default

    In C++. non-const global variable definitions have external linkage by default

    This means to share a constant global, both the declaration AND the definition needs to be extern.

    To share a variable global, only the declaration needs the extern in front of it.  The definition is by default considered external linkage. 

More questions in this forum