Using C++ static class members

sigma_shig
Posts: 6
Joined: Sun Apr 23, 2023 10:19 am

Using C++ static class members

Postby sigma_shig » Sun Apr 23, 2023 10:31 am

Hi.
I'm trying to use my own C++ classes with ESP-IDF (for VSCode). I have a problem with the compilation of very simple application:
hello_world.cpp:

Code: Select all

#include "Class1.h"

extern "C" void app_main(void)
{
    printf("Hello world!\n");
    Class1* c1 = new Class1();
}
Class1.h

Code: Select all

class Class1{
public:
    static int staticField1;
    Class1();
};
Class1.cpp

Code: Select all

#include "Class1.h"
#include <esp_log.h>

Class1::Class1()
{
    ESP_LOGI("Class1", "Constructor");
    staticField1 = 123;
    ESP_LOGI("Class1", "staticField1 = %d", staticField1);
}
When I tried to compile it, I have an error:

Code: Select all

[6/8] Linking CXX executable hello_world.elf 
FAILED: hello_world.elf 
cmd.exe /C "cd . && C:\Users\igorg\.espressif\tools\xtensa-esp32-elf\esp-2022r1-11.2.0\xtensa-esp32-elf\bin\xtensa-esp32-elf-g++.exe -mlongcalls -Wno-frame-address  @CMakeFiles\hello_world.elf.rsp -o hello_world.elf  && cd ."c:/users/igorg/.espressif/tools/xtensa-esp32-elf/esp-2022r1-11.2.0/xtensa-esp32-elf/bin/../lib/gcc/xtensa-esp32-elf/11.2.0/../../../../xtensa-esp32-elf/bin/ld.exe: esp-idf/main/libmain.a(Class1.cpp.obj):(.literal._ZN6Class1C2Ev+0x8): undefined reference to `Class1::staticField1'
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.     
The application is compiled successfully when I comment the last 2 lines with staticField1 usage.
How can I use static fields inside of C++ classes?

Craige Hales
Posts: 94
Joined: Tue Sep 07, 2021 12:07 pm

Re: Using C++ static class members

Postby Craige Hales » Sun Apr 23, 2023 4:10 pm

from https://en.cppreference.com/w/cpp/language/static
class X { static int n; }; // declaration (uses 'static')
int X::n = 1; // definition (does not use 'static')
you've declared it, but not defined it. Look at the end of the long line,
undefined reference to `Class1::staticField1'
Craige

sigma_shig
Posts: 6
Joined: Sun Apr 23, 2023 10:19 am

Re: Using C++ static class members

Postby sigma_shig » Sun Apr 23, 2023 6:28 pm

Thank you. Yep... It's trivial, but I forgot about it.

Who is online

Users browsing this forum: Baidu [Spider] and 120 guests