Check Code Standard Compliance using gcc or g++ Compiler

Check Code Standard Compliance using gcc or g++ Compiler

When writing C or C++ code, it's essential to ensure the code complies with the intended language standard, especially if you're targeting environments that require strict compatibility (e.g., embedded systems, older toolchains, or cross-platform development). This tutorial shows how to check code standard compliance using gcc or g++ compiler.

Here's a quick overview of the key options we'll use:

  • -std=<standard> - sets the C or C++ language standard version.
  • -fsyntax-only - tells the compiler to only check the code for syntax errors, without creating object files or executables.
  • -Wpedantic - enables warnings for code that may be valid in GNU extensions but not strictly conforming to the selected standard.

C Language

Consider the following C code:

int main() {
    _Alignas(32) float data[] = {1, 2, 3, 4, 5};

    return 0;
}

Compile with C11 standard:

gcc -std=c11 -fsyntax-only -Wpedantic main.c

No warnings or errors. The code is valid under the C11 standard, which introduced _Alignas.

Compile with C99 stardard:

gcc -std=c99 -fsyntax-only -Wpedantic main.c

Output:

main.c: In function ‘main’:
main.c:2:5: warning: ISO C99 does not support ‘_Alignas’ [-Wpedantic]
    2 |     _Alignas(32) float data[] = {1, 2, 3, 4, 5};
      |     ^~~~~~~~

The warning indicates that _Alignas is not supported in C99.

C++ Language

Now consider this simple C++ example:

int main() {
    auto data = 10;

    return 0;
}

Compile with C++11 standard:

g++ -std=c++11 -fsyntax-only -Wpedantic main.cpp

No issues. auto type deduction is supported in C++11 and later.

Compile with C++98 standard:

g++ -std=c++98 -fsyntax-only -Wpedantic main.cpp

Output:

main.cpp: In function ‘int main()’:
main.cpp:2:10: error: ‘data’ does not name a type
    2 |     auto data = 10;
      |          ^~~~

The auto keyword in C++98 does not support type deduction, so this code fails to compile.

Leave a Comment

Cancel reply

Your email address will not be published.