-1

Function is declared in hpp file like this:

class StringProcessor
{
    static constexpr const char* string_process(const char* initial_string, std::size_t string_length, const char* key, std::size_t key_length);
};

And defined in cpp like this:

constexpr const char* StringProcessor:: string_process(const char* initial_string, std::size_t string_length, const char* key, std::size_t key_length)
{
     ...
}

How do I call it, because following line throws Undefined symbols for architecture x86_64: "StringProcessor::string_process(char const*, unsigned long, char const*, unsigned long)", referenced from: _main in main.cpp.o error:

std::cout << StringProcessor::string_process("Test", 4, "Test", 4) << std::endl;
THE_CHOODICK
  • 125
  • 6

1 Answers1

3

constexpr functions are implicitly inline and therefore need to be defined in every translation unit where they are used. That usually means that the definition should go into a header shared between the translation units using the function.

Also, in order for constexpr to be of any use, the function needs to be defined before its potential use in a constant expression. Therefore it usually only really makes sense to define it directly on the first declaration, i.e. here in the class definition in the header.

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • Is there a way to explicitly declare it? Maybe something like explicit instantiating like for templates? – THE_CHOODICK Sep 20 '22 at 13:44
  • 2
    @THE_CHOODICK The whole point of `constexpr` is to tell the compiler that the function can be (at least sometimes) evaluated at compile-time. To be able to do that the compiler must know the definition of the function before it is used. So no. – user17732522 Sep 20 '22 at 13:46