You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Všetky globálne premenné sú inicializované pred volaním `main`. Tu jedna závisí od druhej v inom súbore (*translation unit*) a to je nedefinované správanie.
141
+
* Všetky globálne premenné sú inicializované pred volaním `main`. Tu jedna závisí od druhej v inom súbore (*translation unit*) a to je nedefinované správanie.
142
+
143
+
144
+
## Globálne statické premenné
145
+
146
+
* Štandardné globálne premenné sú viditeľné v celom projekte (vo všetkých translation units, sú *external linkage*)
147
+
* Statické globálne premenné sú viditeľné iba v jednom translation unit (sú *internal linkage*)
148
+
149
+
### Pre bežné globálne premenné
150
+
151
+
```cpp
152
+
// file1.cpp
153
+
int global_variable = 67;
154
+
155
+
// file2.cpp
156
+
externint global_variable; // will be the same variable
157
+
```
158
+
159
+
*`extern` hovorí kompilátoru, že táto premenná je definovaná niekde inde a až linker ju spojí dohromady
160
+
*`extern` sa dá použiť aj s funkciami, ak potrebujeme použiť funkciu z iného translation unit, ale nemáme k nemu header súbor
161
+
* Funkcie sú ale `extern` implicitne, teda `int func();` je to isté ako `extern int func();`
162
+
163
+
164
+
### Pre statické globálne premenné
165
+
166
+
```cpp
167
+
// file1.cpp
168
+
staticint static_global_variable = 67;
169
+
170
+
// file2.cpp
171
+
//extern int static_global_variable; // error
172
+
staticint static_global_variable = 43; // different variable
173
+
```
174
+
175
+
```cpp
176
+
// file1.cpp
177
+
int global_variable = 67;
178
+
179
+
// file2.cpp
180
+
staticint global_variable = 43; // different variable
181
+
```
182
+
183
+
184
+
### Bez všetkývch týchto špecifikátorov
185
+
186
+
```cpp
187
+
// file1.cpp
188
+
int global_variable = 67;
189
+
190
+
// file2.cpp
191
+
int global_variable = 43; // error: redefinition of 'global_variable', linker error
192
+
```
193
+
194
+
195
+
### Riešenie pomocou `inline`
196
+
197
+
* V C++17 existuje kľúčové slovo `inline` pre globálne premenné, ktoré umožňuje definovať premennú v hlavičkovom súbore bez linker chyby
0 commit comments