Changing Stack Size for C Applications in Linux with GCC
In Linux, unlike macOS, the LD_FLAGS=-Wl,-stack_size option is not recognized by the GNU compiler. To adjust stack size for a single C application, the setrlimit function can be utilized programmatically.
#include <sys/resource.h> int main() { const rlim_t kStackSize = 16 * 1024 * 1024; // 16 MB struct rlimit rl; int result; // Get current stack size limits result = getrlimit(RLIMIT_STACK, &rl); if (result == 0) { // If current stack size is less than desired, adjust it if (rl.rlim_cur < kStackSize) { rl.rlim_cur = kStackSize; result = setrlimit(RLIMIT_STACK, &rl); if (result != 0) { // Error handling } } } // Your code... return 0; }
When implementing this solution, it's crucial to place large local variable declarations within functions that are called from main() rather than directly in main(). Otherwise, a stack overflow may occur before the stack size can be augmented.
The above is the detailed content of How Can I Change the Stack Size of a C Application in Linux Using GCC?. For more information, please follow other related articles on the PHP Chinese website!