Lone Learner
Lone Learner

Reputation: 20698

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++?

Upvotes: 4

Views: 610

Answers (1)

Yu Hao
Yu Hao

Reputation: 122493

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.

Upvotes: 8

Related Questions