C - access specifiers
In C, the term "access specifiers" (like in C++: public
, private
, protected
) doesn’t actually exist for normal variables and functions — C does not have object-oriented access control.
But C does have ways to control scope and visibility of variables and functions, which serve a similar purpose.
1. Levels of Access Control in C
C controls visibility using:
-
Scope — Where in the code the variable/function can be used.
-
Linkage — Whether it can be accessed from other files.
2. Storage Class Specifiers for Access Control
These are the main keywords that affect "access" in C:
Keyword | Meaning |
---|---|
auto |
Default for local variables (block scope, no linkage) |
static |
Changes scope and lifetime: |
- For global vars/functions → internal linkage (file-level access only)
- For local vars → value persists between calls |
| extern
| Makes a variable/function accessible from other files (external linkage) |
| register
| Suggests storing in CPU registers (scope stays local) — mostly obsolete now |
2.1 File-Level Access
// file1.c
static int hiddenVar = 5; // only accessible in this file
int publicVar = 10; // accessible from other files via extern
static void hiddenFunction() { // only in this file
printf("Hidden\n");
}
void publicFunction() { // accessible from other files
printf("Public\n");
}
// file2.c
#include <stdio.h>
extern int publicVar; // declare to use from file1.c
int main() {
printf("%d\n", publicVar); // OK
// printf("%d", hiddenVar); // ERROR: not visible here
}
2.2 Block Scope
void func() {
int local = 10; // only inside func()
static int persist = 0; // inside func, but keeps value between calls
}
3. Summary Table
Specifier | Scope | Lifetime | Linkage |
---|---|---|---|
auto |
Block | Auto | None |
register |
Block | Auto | None |
static (local) |
Block | Static | None |
static (global) |
File | Static | Internal |
extern |
Global | Static | External |
4. Key Takeaway
-
C doesn’t have
public
/private
/protected
like C++. -
Instead, it uses scope rules (
static
,extern
) to restrict or expose variables/functions. -
static
at file level is the closest thing to "private". -
extern
is the closest thing to "public".