Can I get examples for static keyword in header file?

Viewed 75

static.h

static int y = 20;
static int& f(){
    static int x = 0;
    return x;
}

general.h

int x = 10;
int& g(){
    static int x = 0;
    return x;
}

outer.h

#include"general.h"
#include"static.h"

void h(){
    x = 20;//static
    y = 20;//non static

    f() = 20;//static
    g() = 20;//non static
}

main.cpp

#include<iostream>
#include"static.h"
#include"general.h"
#include"outer.h"

int main(){
    h();
    std::cout<<"static objects are independent in each file\n";
    std::cout<<"x : "<<x<<", f() : "<<f()<<std::endl;
    std::cout<<"non static objects are only one in every file.\n ";
    std::cout<<"y : "<<y<<", g() : "<<g()<<std::endl;
}

I want to simulate how static keyword changes code behavior.
but, I don't know how to do that...
How do I do?

.....................................................
I split my code.
static.h

static int x = 0;
static int& f(){
    static int k = 0;
    return k;
}
void call_static();

static.cpp

#include"static.h"

void call_static(){
    x = 10;
    f() = 10;
}

general.h

int y = 0;
int& g(){
    static int z = 0;
    return z;
}
void call_general();

general.cpp

#include"general.h"
void call_general(){
    y = 10;
    g() = 10;
}

Static codes are compiled well, but non static codes aren't compiled.

error code

/usr/bin/ld: /tmp/general-539e11.o: in function `g()':
general.cpp:(.text+0x0): multiple definition of `g()'; /tmp/main-5f12cd.o:main.cpp:(.text+0x0): first defined here
/usr/bin/ld: /tmp/general-539e11.o:(.bss+0x0): multiple definition of `y'; /tmp/main-5f12cd.o:(.bss+0x4): first defined here
clang-12: error: linker command failed with exit code 1 (use -v to see invocation)

Is it normal?

1 Answers

In the example you've shown there's only one .cpp file.
.h files don't actually count as "Translation Units", only .c and .cpp files are translation units.
The reason for that is that .h files are added to a program using #include.
#include literally copy-pastes the specified file into the current file, making it just 1 big file.
If you had multiple .c or .cpp files (or a mix of both, that's OK as well), you'll be able to see the effects that the static keyword has on variable/function visibility.

Remember to NEVER #include .c or .cpp files!
Instead, you should add them to your program seperately.
If you are using Visual Studio (not VS Code) simply adding a new source file should automatically add it to the program, without you needing to mention it anywhere.
If you are using another compiler, add the name of your .c or .cpp files to the list of files to be compiled.

I'd reccomend reading about translation units.
you can do that at https://en.wikipedia.org/wiki/Translation_unit_(programming) and What is a "translation unit" in C++?, but I'd also highly recommend just looking up "c and c++ translation units" on google and learning about them in general.

Have fun coding!

Related