Static inline variable defined in header is being initialised more than once

1 day ago 1
ARTICLE AD BOX

I was under the impression that static inline variables are only initialised once:

// foo.hpp #pragma once #include <string> #include <chrono> static const inline std::string FOOBAR_DIR = "/foobar_" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + "/";

I thought that if foo.hpp is included in multiple source files, both would see the same value for FOOBAR_DIR as initialisation would only happen once. But this doesn't seem to be the case in my Catch2 tests.

In my Catch2 tests, I have an event listener that uses FOOBAR_DIR:

#include <catch2/reporters/catch_reporter_event_listener.hpp> #include <catch2/reporters/catch_reporter_registrars.hpp> #include <filesystem> #include "foo.hpp" class SomeEventListener: public Catch::EventListenerBase { public: using Catch::EventListenerBase::EventListenerBase; void testRunStarting(const Catch::TestRunInfo&) override { std::filesystem::create_directories(FOOBAR_DIR); } void testRunEnded(const Catch::TestRunStats&) override { std::filesystem::remove_all(FOOBAR_DIR); } }; CATCH_REGISTER_LISTENER(SomeEventListener)

In addition, I make use of FOOBAR_DIR in another source file, in a test case:

#include <catch2/catch_test_macros.hpp> #include "foo.hpp" TEST_CASE("some test case", "[some-tag]") { // Do something with FOOBAR_DIR }

The problem is that FOOBAR_DIR is being initiated twice, once for each source file that makes use of it.

Is there something that I'm doing wrong that is resulting in this behaviour? Should static inline variables be initiated multiple times if they are accessed in multiple source files?

I'm using GCC 14 on Linux AMD64

Read Entire Article