Change stack size for a C++ application in Linux during compilation with GNU compiler

You can set the stack size programmatically with setrlimit, e.g.

#include <sys/resource.h>

int main (int argc, char **argv)
{
    const rlim_t kStackSize = 16 * 1024 * 1024;   // min stack size = 16 MB
    struct rlimit rl;
    int result;

    result = getrlimit(RLIMIT_STACK, &rl);
    if (result == 0)
    {
        if (rl.rlim_cur < kStackSize)
        {
            rl.rlim_cur = kStackSize;
            result = setrlimit(RLIMIT_STACK, &rl);
            if (result != 0)
            {
                fprintf(stderr, "setrlimit returned result = %d\n", result);
            }
        }
    }

    // ...

    return 0;
}

Note: even when using this method to increase stack size you should not declare large local variables in main() itself, since you may well get a stack overflow as soon as you enter main(), before the getrlimit/setrlimit code has had a chance to change the stack size. Any large local variables should therefore be defined only in functions which are subsequently called from main(), after the stack size has successfully been increased.

Leave a Comment