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

前端 未结 4 1812
轻奢々
轻奢々 2020-11-22 03:42

In OSX during C++ program compilation with g++ I use

LD_FLAGS= -Wl,-stack_size,0x100000000

4条回答
  •  感情败类
    2020-11-22 04:30

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

    #include 
    
    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.

提交回复
热议问题