Using C++ static class members
Posted: 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:
Class1.h
Class1.cpp
When I tried to compile it, I have an error:
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?
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();
}
Code: Select all
class Class1{
public:
static int staticField1;
Class1();
};
Code: Select all
#include "Class1.h"
#include <esp_log.h>
Class1::Class1()
{
ESP_LOGI("Class1", "Constructor");
staticField1 = 123;
ESP_LOGI("Class1", "staticField1 = %d", staticField1);
}
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.
How can I use static fields inside of C++ classes?