Is there a length limit on g++ variable names?
Asked Answered
L

3

22

See title​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Lightly answered 21/4, 2010 at 10:23 Comment(1)
There may be an implementation limit on significant characters in external identifiers (e.g. the linker's allowed to treat foobarbaz and foobarqux as the same variable). It's recommended in C++17 that at least 1024 characters of significance be supported but there is no minimum limit mandated.Epenthesis
D
24

Short Answer:

No

Long Answer:

Yes, it has to be small enough that it will fit in memory, but otherwise no, not really. If there is a builtin limit (I don't believe there is) it is so huge you'd be really hard-pressed to reach it.

Actually, you got me really curious, so I created the following Python program to generate code:

#! /usr/bin/env python2.6
import sys;
cppcode="""
#include <iostream>
#include <cstdlib>

int main(int argc, char* argv[])
{
     int %s = 0;
     return 0;
}
"""

def longvarname(n):
    str="x";
    for i in xrange(n):
        str = str+"0";
    return str;

def printcpp(n):
    print cppcode % longvarname(n);

if __name__=="__main__":
    if len(sys.argv)==2:
        printcpp(int(sys.argv[1]));

This generates C++ code using the desired length variable name. Using the following:

./gencpp.py 1048576 > main.cpp
g++ main.cpp -o main

The above gives me no problems (the variable name is roughly 1MB in length). I tried for a gigabyte, but I'm not being so smart with the string construction, and so I decided to abort when gencpp.py took too long.

Anyway, I very much doubt that gcc pre-allocates 1MB for variable names. It is purely bounded by memory.

Dundalk answered 21/4, 2010 at 10:32 Comment(2)
I did something similar before this - I'll post the code (its on another machine), but basically a python function that generated C++ code with 2 variables with a differing last character to ensure that the names that long are distinct. I got to 64k and thought that is enough. Not tried with 1Mb though.Schriever
on my win32 mingw the compiler/ld cannot link your sampleRectifier
E
4

an additional gotcha, some linkers have a limit on the length of the mangled name. this tends to be an issue with template and nested classes more than identifier length but either could trigger a problem afaik

Ebba answered 21/4, 2010 at 10:52 Comment(0)
L
2

I don't know what the limit is (or if there is one), but I think it is good practice that there should be one, in order to catch pathological code, for example that created by a runaway code generator. For what it's worth, the C++ Standard suggests a minimum of 1K for identifier length.

Lightly answered 21/4, 2010 at 10:50 Comment(1)
@Neil, I don't think it's the compiler's responsibility to catch the runaway code generator. Allowing for an arbitrary length as permitted by hard resource constraints seems the most sensible thing to me.Dundalk

© 2022 - 2024 — McMap. All rights reserved.