In contrast to macOS, where LD_FLAGS can be employed to specify stack size during C compilation with g , Linux distributions like SUSE Linux display errors when encountering such a command. This issue arises due to the unavailability of the --stack option within the Linux linker.
To circumvent this obstacle, an alternative approach involves setting the stack size programmatically within the application itself. Leveraging the setrlimit function, developers can modify the stack size after compiling the application. Here's an illustrative code snippet:
#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; }
Please note that utilizing this method requires avoiding declaring large local variables within the main() function, as this could lead to a stack overflow before the stack size adjustment is executed. Instead, define these variables in functions called from main(), once the stack size has been successfully modified.
The above is the detailed content of How to Modify C Application Stack Size in Linux During Compilation?. For more information, please follow other related articles on the PHP Chinese website!