Как сохранить вывод ошибок gcc в файл - PullRequest
5 голосов
/ 02 августа 2011

Когда я компилирую свой код, я получаю кучу ошибок, которые я пролистываю по экрану, и я вижу, где начинается ошибка. Как я могу сохранить вывод gcc в файл?

Я пробовал такие трюки, как

gcc> log.txt

или вывод результатов, но это не сработало. Поиск в Google дает в основном объяснение того, как печатать в файл с помощью c ++

Ответы [ 2 ]

16 голосов
/ 02 августа 2011

GCC выводит ошибки в поток standard error , а не в поток standard output .Вам нужно перенаправить стандартную ошибку вместо стандартного вывода .В баш:

gcc 2> log.txt
10 голосов
/ 11 октября 2013

Лично я обнаружил, что просто вывод ошибки в файл не поможет.На самом деле, самая простая вещь, которая могла мне помочь, - это избегать переноса строк ошибок, которые обычно бывают очень длинными.Поэтому я решил использовать vim подсветку, чтобы лучше видеть ошибки.

Без маркера ( Просмотреть увеличенное изображение )

Screenshot - Before

С маркером ( Просмотреть увеличенное изображение )

Screenshot - After.

И, к счастью, был очень простой способ настроить подсветку нового синтаксиса в VIM.Выполните следующие шаги, и вы будете более продуктивно работать с сильно шаблонизированными кодами C ++:

Создайте новый набор правил подсветки синтаксиса VIM

, вам нужно определить правила подсветки синтаксиса.Поместите следующее в файл с именем cerr.vim и сохраните его, например, в $HOME/vim_syntax/cerr.vim

"Set line wrapping to off to see more error lines in one page
set nowrap                   
set showmatch
"I use stl and boost alot so it is good to remove the namespaces from the error file :)
silent! %s/st![enter image description here][2]d:://g                                                
silent! %s/boost::fusion:://g                                                  
silent! %s/boost:://g                                                
"Usually I am not interested in the file paths until I can locate the error so I tried to
"hide them
silent! %s/\/[^\.]*\//   /g                                                    
"By default syntax highlighting for each line is limited to 3000 characters    
"However, 3000 characters is not sufficient for lengthy C++ errors, so I change it to 20000
set synmaxcol=20000                                                            
"Now I define the keywords that I would like them to be highlighted
syn keyword cerrInfo instantiated                                             
syn keyword cerrError error Error ERROR                                       
syn keyword cerrWarning warning Warning WARNING

"-------------------------------------                                         
"In this step I would like to distinguish the prefix in each line (which shows the file name) from the rest of the line
syn region cerrLine start=/^/ end=/\:/                                        
syn region cerrSeparator start=/^\.+/ end=/\./ fold oneline

"I want to make templated type information less visible while debugging              
"You have to remember that a type can have nested types. So I define three regions
syn region cerrTemplate1 matchgroup=xBracket1 start=/</ end=/>/ contains=cerrTemplate2 fold oneline
syn region cerrTemplate2 matchgroup=xBracket2 start=/</ end=/>/ contains=cerrTemplate3 fold contained oneline
syn region cerrTemplate3 start=/</ end=/>/ contains=cerrTemplate3 contained oneline fold oneline

"Now I would like to highlight whatever is in parenthesis with a different color so I make
"another region in here. This makes sure that function arguments can have different color            
 syn region cerrPar matchgroup=xBracket start=/(/ end=/)/ contains=cerrTemplate1 oneline fold
"GCC puts the real type information in brackets, let's group them separately
 syn region cerrBracket start=/\[/ end=/\]/ contains=cerrTemplate1,cerrPar oneline

"Again GCC puts the error in these weird characters :) So I define a separate region here
syn region cerrCode start=/‘/ end=/’/ contains=cerrPar,cerrBracket,cerrTemplate1 oneline

"And finally I would like to color the line numbers differently
syn match   cerrNum "[0-9]\+[:|,]"                                            

"--------------------------------------------------------------------------
"Now the fun part is here, change the colors to match your terminal colors. 
"I Use the following colors for my white background terminal.
"In the following we assign a color for each group that we defined earlier

"Comment is a default VIM color group
highlight link cerrInfo Comment     
"We use custom coloring for the rest                                          
highlight default cerrWarning ctermfg=red ctermbg=yellow                      
highlight default cerrError ctermfg=white ctermbg=red                         
highlight default cerrLine ctermfg=grey term=bold                             
highlight default cerrSeparator ctermfg=darkgrey                              
highlight default cerrTemplate1 ctermfg=grey term=bold                        
highlight default cerrTemplate2 ctermfg=grey term=bold                        
highlight default cerrTemplate3 ctermfg=grey                                  
highlight default cerrCode cterm=bold ctermfg=darkgrey                        
highlight default cerrBracket ctermfg=darkgreen                               
highlight default xBracket1 ctermfg=darkgrey term=bold                         
highlight default xBracket2 ctermfg=darkgrey                                   
highlight default cerrPar ctermfg=yellow                                      
highlight default cerrNum ctermfg=red

Измените свой файл .vimrc

Теперь вы должны указать vim использовать ваш новыйвыделение для файлов с определенным расширением.В моем случае я хотел бы вывести мои файлы ошибок в error.ccerr , поместите в ваш .vimrc в вашей домашней папке следующее:

au BufRead,BufNewFile *.cerr set filetype=myerror
au Syntax myerror source $HOME/vim_syntax/cerr.vim  

То, что я говорю выше:что когда файлы с расширением .cerr открываются с использованием VIM, они рассматриваются как тип myerror.Во второй строке я говорю, что VIM должен использовать мой набор правил подсветки синтаксиса, который я определил на предыдущем шаге для всех файлов myerror.

Отправьте вывод ошибок в файл .cerr и откройте его с помощью VIM

Этот шаг самый простой, мы отправляем все ошибки и предупреждения в error.cerr, и если вфайл мы немедленно открываем .cerr файл, используя VIM.

g++ failing.cc &> error.cerr || vim error.cerr
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...