2015-01-13 57 views
0

我正在尝试制作一个程序。这是通过gcc编译器从C代码打印错误。 编译错误发生时,它会生成错误消息中的文本文件。但运行时错误发生时。例如,“分段错误”。该文件是空的。 它在终端上很好地显示了分段错误,但它不显示文件中的错误。如何将gcc运行时错误打印到文本文件?

我试着在几条命令下键入,但它仍然不起作用。

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

你说的是GCC本身的运行时错误? –

+0

我认为,gcc会产生编译错误的文件。但是,运行时错误.... –

+0

那么,我不知道如何让海湾合作委员会抛出seg-fault,所以我很难重现! –

回答

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; 
} 

通常情况下,我会做以下步骤编译之前:

[email protected]:~/Work/c/test_coredump 
-> ulimit -c 
0 
[email protected]:~/Work/c/test_coredump 
-> ulimit -c unlimited 
[email protected]:~/Work/c/test_coredump 
-> ulimit -c 
unlimited 
[email protected]:~/Work/c/test_coredump 
-> gcc -g ./test_coredump.c 
[email protected]:~/Work/c/test_coredump 
-> ls 
a.out test_coredump.c 
[email protected]:~/Work/c/test_coredump 
-> ./a.out 
Segmentation fault (core dumped) 

在此之后,它会为你生成核心转储文件:

[email protected]:~/Work/c/test_coredump 
-> ls 
a.out core test_coredump.c 

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

[email protected]:~/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) 

你可以找到你在哪里编程陷阱。

+0

谢谢你的回答。这是一个好方法!还有一个问题,你能提取'gdb ./a.out ./core'文件的结果吗?非常感谢!! –

+0

@ user3422425,我没有试过,因为当我运行'gdb ./a.out。/ core'时,'gdb1正在运行。我尝试'gdb ./a.out ./core> log',但shell等待'gdb'的输入等待,我可以输入'q'来退出'gdb',然后你可以在你的日志文件中找到上面的日志。然而,'core'文件已经包含了你需要的所有消息,我认为它是LOG :),但是你需要'gdb'来解码。 –

+0

太棒了!我认为悬而未决的问题,我们可以杀死任务。再次感谢你。 –

0

本应该把错误的文件中正确:

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

谢谢。但是,error.log文件仍然是空的。 –

0

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

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

但是,Segmentation fault消息不是由您的程序生成的。它由操作系统生成,并打印在shell的stderr(不是您的程序的stderr)上。重定向这个消息取决于你的shell,见this question

相关问题