如何将 gcc 运行时错误打印到文本文件?

How to print gcc runtime error to text file?

我正在尝试制作一个程序。那是通过 gcc 编译器从 C 代码打印错误。 当发生编译错误时,它会生成包含错误消息的文本文件。但是当发生运行时错误时。例如,'segmentation fault'。该文件为空。 它在终端上很好地显示了分段错误,但没有显示文件中的错误。

我尝试输入以下几个命令,但仍然无效。

gcc new.c &> myFile
gcc new.c > myFile 2>&1

这应该将错误正确地放入文件中:

gcc new.c -o new.x >& error.log

我认为你需要核心转储文件但没有捕获 gcc

的 运行 时间错误

我告诉你如何在 Linux 下获取核心转储,我写了一个测试程序,test_coredump.c:

#include <stdlib.h>

int main(void){
    int *ptr = NULL;
    *ptr = 10;  //Segmentation fault will happen since you write to a null memory

    return 0;
}

一般情况下,我会在编译前做以下步骤:

how@ubuntu-sw:~/Work/c/test_coredump
-> ulimit -c
0
how@ubuntu-sw:~/Work/c/test_coredump
-> ulimit -c unlimited
how@ubuntu-sw:~/Work/c/test_coredump
-> ulimit -c
unlimited
how@ubuntu-sw:~/Work/c/test_coredump
-> gcc -g ./test_coredump.c
how@ubuntu-sw:~/Work/c/test_coredump
-> ls
a.out  test_coredump.c
how@ubuntu-sw:~/Work/c/test_coredump
-> ./a.out 
Segmentation fault (core dumped)

之后,它会为您生成核心转储文件:

how@ubuntu-sw:~/Work/c/test_coredump
-> ls
a.out  core  test_coredump.c

你可以知道使用 gdb 或任何你喜欢的调试工具:

how@ubuntu-sw:~/Work/c/test_coredump
-> gdb ./a.out ./core 
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
[New LWP 6421]
Core was generated by `./a.out'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x080483fd in main () at test_coredump.c:5
5       *ptr = 10;  //Segmentation fault will happen since you write to a null memory
(gdb)

你可以找到你编程陷阱的地方。

gcc 编译程序。重定向 gcc 的输出不会帮助您解决程序成功编译 运行s 后出现的任何错误。

到运行你的程序并将你程序的stderr重定向到一个文件,你可以写./yourprogramname 2>file.txt.

但是,Segmentation fault 消息也不是由您的程序生成的。它由操作系统生成并打印在 shell 的 stderr 上(不是您程序的标准错误)。要重定向此消息,它取决于您的 shell,请参阅 this question