Skip to content

[Clang] Linker error at -O0 due to missing static const int definition, hidden at -O2 #139227

Closed
@shzaiz

Description

@shzaiz

In Clang 20.1.0, a class with static const int members that are declared but not defined results in a linker error at -O0, but compiles successfully at -O2.

This seems to be due to constant propagation at higher optimization levels, which removes the need for symbol resolution, masking the fact that a required definition is missing.

This behavior differs from MSVC, which compiles successfully in both optimization levels.

Code:

#include <map>
#include <vector>
using namespace std;
const pair<int, int> START = make_pair(0, 0);
class GridWorld {
public:
    // change `const' to `constexpr', it will successfully execute
    // or change compiler option with -O2
    static const int NORTH = 123456, SOUTH = 1, EAST = 2, WEST = 3;
    typedef pair<int, int> State;
    GridWorld(int x = 0, int y = 0) {}
    State state() { return make_pair(x, y); }
    map<State, double> benefit_matrix;
    void learn_benefit() {
        GridWorld temp(0, 0);
        for (auto action_state : temp.available_actions())
            ;
    }
private:
    int x, y;
    vector<pair<int, State>> available_actions() {
        vector<pair<int, State>> actions;
        if (y != 0)
            actions.push_back(make_pair(NORTH, make_pair(x, y - 1)));
        if (y != 4)
            actions.push_back(make_pair(SOUTH, make_pair(x, y + 1)));
        if (x != 4)
            actions.push_back(make_pair(EAST, make_pair(x + 1, y)));
        if (x != 0)
            actions.push_back(make_pair(WEST, make_pair(x - 1, y)));
        return actions;
    }
};

int main() {
    GridWorld env = GridWorld(START.first, START.second);
    env.learn_benefit();
    return 0;
} 

Reproduction Link: https://godbolt.org/z/dTdxWzMjP

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:codegenIR generation bugs: mangling, exceptions, etc.diverges-from:msvcDoes the clang frontend diverge from msvc on this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions