Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a C++ header file is correct with gcc tools?

Tags:

c++

gcc

header

How can I check if the syntax of a header file is correct with gcc tools?

like image 838
lknfdhu Avatar asked Mar 29 '11 16:03

lknfdhu


People also ask

How does GCC search for header files?

GCC looks for headers requested with #include " file " first in the directory containing the current file, then in the directories as specified by -iquote options, then in the same places it would have looked for a header requested with angle brackets. For example, if /usr/include/sys/stat. h contains #include "types.

How do you check if a header file is included?

To check if an header file has been included or not in a C or C++ code, we need to check if the macro defined in the header file is being defined in the client code. Standard header files like math. h have their own unique macro (like _MATH_H ) which we need to check. Consider this example of checking if math.

Which option in GCC is used to specify the location of the .h files?

gcc -I adds include directory of header files.

Does GCC need header files?

GCC needs to install corrected versions of some system header files. This is because most target systems have some header files that won't work with GCC unless they are changed. Some have bugs, some are incompatible with ISO C, and some depend on special features of other compilers.


2 Answers

-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.

like image 31
NPE Avatar answered Sep 26 '22 07:09

NPE