linker error C++

Technical questions regarding the XTC tools and programming with XMOS.
User avatar
fabriceo
Respected Member
Posts: 282
Joined: Mon Jan 08, 2018 4:14 pm

linker error C++

Post by fabriceo »

Hello
I get a warning by the linker when using static variables in a c++ class:
dsp_app.cpp: Warning: Undefined reference to '_ZN7Counter5countE'

Code: Select all

class Counter { 
public:
    static unsigned count;
    Counter() { count++; }
};

void test() {
    Counter c;
    debug_printf("count %d\n", c.count );
}
FYI, I have added -std=c+11 in the XCC_FLAGS. using XTC15.3.1
this is not a template class requiring some specialisation
any suggestion ??
Thank you !
fabriceo
User avatar
xhuw
Verified
Experienced Member
Posts: 64
Joined: Wed May 22, 2024 2:36 pm

Post by xhuw »

I cannot reproduce this.

however according to the C++ spec https://en.cppreference.com/w/cpp/language/static.html static members should be defined out of line OR with the inline keyword:

Code: Select all

class Foo {
public:
  static unsigned count;
};
unsigned Foo::count;

// OR
class Foo {
public:
  static inline unsigned count;
};

XMOS Software Engineer

Image
User avatar
fabriceo
Respected Member
Posts: 282
Joined: Mon Jan 08, 2018 4:14 pm

Post by fabriceo »

hi xhuw; thank you for your attention.
I confirm the problem but it comes from the debug_print trying to get c.count
if I implement a get() inside Counter to retrieve count, then debug_print is happy calling c.get() and linker also.

so I m fine with this "workaround" but still surprised about the error message.

about "inline", the compiler throw an error message "'inline' can only appear on functions"

FYI, I made the tests by adding a cpp file in the "extension" folder of evk_316 application, and using the test() inside audiohw.xc audiohwinit()
thanks again
Fabrice
User avatar
xhuw
Verified
Experienced Member
Posts: 64
Joined: Wed May 22, 2024 2:36 pm

Post by xhuw »

having another look at cppreference I can see that inline was added in C++17 (my mistake).
XMOS Software Engineer

Image
User avatar
xhuw
Verified
Experienced Member
Posts: 64
Joined: Wed May 22, 2024 2:36 pm

Post by xhuw »

You need to define the static variable out side of the class where is it declared

Code: Select all

class Counter { 
public:
    static unsigned count;
    Counter() { count++; }
};
unsigned Counter::count;
this is not a workaround as it is part of the C++11 specification. it solves the issue
XMOS Software Engineer

Image
User avatar
fabriceo
Respected Member
Posts: 282
Joined: Mon Jan 08, 2018 4:14 pm

Post by fabriceo »

thanks xhuw, you are right, the static member can be "declared" inside the class but it doesn't really exist until it is defined with a specific statement in the core program. my bad.