Specifying the standard with -std= flags
What you'll learn: How to tell your compiler exactly which version of the C language rules to follow when building your program.
The Language Time Machine
C is an evolving language. Over the decades, it has gone through several major revisions, such as C89, C99, C11, and C17. You can think of these like different editions of a rulebook. If you write code using modern "slang" (features) from the 2011 rulebook, but your compiler is trying to read it using the 1989 rulebook, it will get confused and throw an error.
By default, modern compilers like GCC or Clang use a relatively recent version of C, but they also include "extensions"—extra features that aren't part of the official standard. To ensure your code is portable and behaves exactly as you expect, you should manually specify the standard using the -std= flag.
How to Use the Flag
When you compile your code in the terminal, you add the flag followed by the version name. Common values include c89, c99, c11, and c17.
For example, if you want to use C99 (which introduced the ability to declare variables inside a for loop), you would compile like this:
gcc -std=c99 main.c -o my_program
Why This Matters
Imagine you are building a Lego set. If you mix instructions from a 1980s set with pieces from a 2024 set, some things might fit, but others will be frustratingly incompatible. By setting the -std= flag, you are telling the compiler, "Ignore your own preferences; use exactly these rules."
This is crucial for portability. If you write code using -std=c11, you can be confident that another developer using a different compiler (like Clang instead of GCC) will be able to build your project as long as they also use the C11 flag. It prevents "it works on my machine" syndrome caused by different compiler defaults.
Code Example: C89 vs. C99
In the original C89 standard, you couldn't do this:
#include <stdio.h>
int main() {
// This style of declaration requires -std=c99 or higher
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
If you try to compile the code above with gcc -std=c89, the compiler will complain because int i inside the loop wasn't allowed yet. Specifying -std=c99 tells the compiler to allow it.
Key takeaway
Use the -std= flag to ensure your compiler follows a specific version of the C standard, making your code predictable and portable across different systems.