Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler complain about undefined reference to a constexpr function even though it is defined in another source file?

I have source code in two files.

The first file contains int main() function and declaration and usage of constexpr int square(int x) function.

// File: foo.cpp
#include <iostream>

constexpr int square(int x);

int main()
{
    int a = square(10);
    std::cout << "a: " << a << "\n";
}

The second file contains the definition of constexpr int square(int x) function.

// File: bar.cpp
constexpr int square(int x)
{
    return x * x;
}

When I try to compile these two files, I get the following error.

$ g++ -std=c++11 bar.cpp foo.cpp
foo.cpp:4:15: warning: inline function ‘constexpr int square(int)’ used but never defined
 constexpr int square(int x);
               ^
/tmp/cc7iwVDZ.o: In function `main':
foo.cpp:(.text+0xe): undefined reference to `square(int)'
collect2: error: ld returned 1 exit status

If I remove the constexpr keyword from both source files, then the program compiles and runs fine.

$ sed 's/constexpr//g' foo.cpp > foo2.cpp
$ sed 's/constexpr//g' bar.cpp > bar2.cpp
$ g++ -std=c++11 bar2.cpp foo2.cpp
$ ./a.out 
a: 100

Why does the program not compile when the constexpr keyword is present? Why does it complain about undefined reference to square(int) when it is clearly present in 'bar.cpp' specified as command line argument to g++?

like image 692
Lone Learner Avatar asked Mar 16 '23 01:03

Lone Learner


1 Answers

When the compiler can do so, it will replace a call to a constexpr function with its resulting value. As a result, constexpr functions are implicitly inline.

Normally you should define constexpr functions in headers.

like image 188
Yu Hao Avatar answered Apr 27 '23 14:04

Yu Hao