DEV Community

제민욱
제민욱

Posted on

Global vs Static in C++

Key Differences

Aspect Global Variable Static Variable
Scope Accessible throughout program Limited to file, function, or class scope
Visibility Shared across files (extern) Restricted to declaring scope
Lifetime Entire program duration Entire program duration

Example Code

Global Variable

// globals.cpp
int globalVar = 42; // Global variable

// main.cpp
#include <iostream>
extern int globalVar; // Declaration for the global variable from another file

void modifyGlobal() {
    globalVar++; // Accessible across files
}

int main() {
    modifyGlobal();
    std::cout << "Global Variable: " << globalVar << std::endl; // Prints: 43
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

File-Scope Static Variable

#include <iostream>

static int staticVar = 10; // File-scope static

void modifyStatic() {
    staticVar++; // Accessible only within this file
}

int main() {
    modifyStatic();
    std::cout << "Static Variable: " << staticVar << std::endl; // Prints: 11
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Function-Scope Static Variable

#include <iostream>

void counter() {
    static int count = 0; // Retains value across calls
    count++;
    std::cout << "Count: " << count << std::endl;
}

int main() {
    counter(); // Prints: 1
    counter(); // Prints: 2
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more