How to check if a C++ header file is correct with gcc tools?
How can I check if the syntax o开发者_运维知识库f a header file is correct with gcc tools?
-fsyntax-only
Does exactly what you want:
echo 'int i;' > good.hpp
echo 'int i' > bad.hpp
g++ -fsyntax-only good.hpp
echo $?
# 0
g++ -fsyntax-only bad.hpp
# bad.hpp:1:5: error: expected initializer at end of input
# int i
# ^
echo $?
# 1
g++ --version | head -n1
g++ (Ubuntu 4.8.1-2ubuntu1~12.04) 4.8.1
man g++
says:
-fsyntax-only
Check the code for syntax errors, but don't do anything beyond that.
You could try compiling it with g++
, as in g++ -c myheader.h
. This will catch any syntax errors.
make a cpp file which does but include the header and compile it ;)
I usually ensure that every header is included by a source file. If, for example, a library I'm developing is header-only, I specifically write a bare-bones unit test specifically to include any stand-alone headers, and test instantiation of any templates in that header.
精彩评论