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

时间:2015-01-13 08:14:44

标签: c gcc

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

我尝试输入以下几个命令,但它仍然不起作用。

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我认为您需要核心转储文件但不能捕获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)

你可以找到编程陷阱的位置。

答案 2 :(得分:0)

gcc编译程序。重定向gcc的输出将无法帮助您解决程序成功编译后运行时出现的任何错误。

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

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