vendredi 13 septembre 2019

std::min and constexpr give a linker error

Trying to use std::min I am getting linker errors passing a value from a const referenced struct and a static const expression. Here is a summary of my code:

#include <algorithm>
#include <cstdint>

struct Settings {
  uint32_t a;
}

class X 
{
public:

  static constexpr uint32_t MAX_A = 10;

  void some_function(const Settings& settings) 
  {
    // Using settings.a and MAX_A here in a different statement.

    uint32_t a = std::min(settings.a, MAX_A);
  }
};


The error received is: undefined reference to "X::MAX_A"

This code compiles fine on godbolt using ARM gcc 8.2 -O2 -std=gnu++11. Locally on my machine it does not. I can fix the problem by casting the constexpr when passing it to std::min: uint32_t a = std::min(settings.a, static_cast<uint32_t>(MAX_A));.

Do you have any suggestion on why this error is a linker error and not a compiler error? Why is this fixed when adding the static cast even though MAX_A is already defined as an uint32_t?

Aucun commentaire:

Enregistrer un commentaire