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?