1

I have something similar to the following code :

include/Group.hpp

#pragma once    
#include <initializer_list>      
struct Group {
  static constexpr std::initializer_list<int> v = {1,2,3};    
};

include/foo.hpp

#pragma once
void foo();

src/foo.cpp

#include <foo.hpp>
#include <Group.hpp>
#include <vector>

void foo(){
  std::vector<int> a{Group::v};
}

src/main.cpp

#include <vector>
#include <Group.hpp>
#include <foo.hpp>

int main()
{
  std::vector<int> b{Group::v}; // this
  foo();                        // or this, but not both
  return 0;
}

When compiled with g++ -std=c++17 -O1 -Iinclude src/foo.cpp src/main.cpp, it produced the following errors :

`._0' referenced in section `.text' of /tmp/ccojX9pJ.o: defined in discarded section `.rodata.._0[_ZN5Group1vE]' of /tmp/ccojX9pJ.o
`._0' referenced in section `.text' of /tmp/ccojX9pJ.o: defined in discarded section `.rodata.._0[_ZN5Group1vE]' of /tmp/ccojX9pJ.o
collect2: error: ld returned 1 exit status

To be sure, c++filt _ZN5Group1vE returns Group::v.

The error disappears when the call to either foo() or std::vector constructor is commented in main. Am I touching some undefined behavior here or is there a bug in the compiler?

I'm using compiler g++ (GCC) 8.3.1 20190223 (Red Hat 8.3.1-2).

Note: The code compiles without error with clang++ (clang) version 7.0.1 (Fedora 7.0.1-6.fc29)

Eskilade
  • 84
  • 2
  • 11
  • I'm not entirely sure what the resolution is regarding the legality of declaring a `static constexpr std::initializer_list`: https://stackoverflow.com/q/16063123/8360627 https://stackoverflow.com/q/27496004/8360627 Are you able to replace it with `std::array`? – John Ilacqua Jan 30 '20 at 02:48
  • I need to be able to define members of different lengths in `Group`. Since the size is part of the type of `std::array`, the different members would no longer have the same type, and so makes it more tedious to declare and use. My current work around is to declare the members `static const` as they're not used in a `constexpr` context _yet_. What I would like to know is whether this code is legal and whether there's a bug in the `gcc 8.3` – Eskilade Jan 30 '20 at 10:07

0 Answers0