在使用GNU编译器进行编译期间,在Linux中更改C ++应用程序的堆栈大小 [英] Change stack size for a C++ application in Linux during compilation with GNU compiler
问题描述
在使用 g ++
编译C ++程序期间,OSX使用
LD_FLAGS = -Wl,-stack_size,0x100000000
但是在SUSE Linux中,我经常会遇到如下错误:
$ b
x86_64-suse-linux / bin / ld:无法识别的选项'--stack'
以及类似的。
我知道可以使用
ulimit -s无限
但这并不好,因为并非所有用户都能这样做。
如何通过GCC为单个应用程序增加Linux中的堆栈大小?
>您可以使用 setrlimit 以编程方式设置堆栈大小,例如 #include
int main(int argc,char ** argv)
{
const rlim_t kStackSize = 16 * 1024 * 1024; //最小堆栈大小= 16 MB
struct rlimit rl;
int结果;
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\\\
,result);
}
}
}
// ...
return 0;
}
注意:即使使用此方法增加堆栈大小,也不应声明大本地变量在 main()
本身中,因为只要输入 main()
,在 getrlimit
/ setrlimit
代码之前有机会更改堆栈大小。因此,任何大的局部变量只能在堆栈大小成功增加后才能在 main()
中调用的函数中定义。
In OSX during C++ program compilation with g++
I use
LD_FLAGS= -Wl,-stack_size,0x100000000
but in SUSE Linux I constantly get errors like:
x86_64-suse-linux/bin/ld: unrecognized option '--stack'
and similar.
I know that it is possible to use
ulimit -s unlimited
but this is not nice as not always can a single user do that.
How can I increase the stack size in Linux with GCC for a single application?
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.
这篇关于在使用GNU编译器进行编译期间,在Linux中更改C ++应用程序的堆栈大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!