Skip to content

Commit 2e087d1

Browse files
authored
Update README.md
1 parent 02d6ffa commit 2e087d1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

basic_content/static/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,3 +246,32 @@ int main()
246246
Welcome to Apple!
247247
```
248248

249+
**限定访问范围**
250+
static还有限定访问范围的作用(类似于匿名名字空间)。来自issue:https://github.com/Light-City/CPlusPlusThings/issues/142
251+
252+
// source1.cpp
253+
extern void sayHello();
254+
const char* msg = "Hello World!\n";
255+
int main()
256+
{
257+
sayHello();
258+
return 0;
259+
}
260+
261+
// source2.cpp
262+
#include <cstdio>
263+
extern char* msg;
264+
void sayHello()
265+
{
266+
printf("%s", msg);
267+
}
268+
g++对于上面两个代码文件是可以正常编译并且打印Hello World!,但如果给source1.cpp中的msg加上static,则会导致undefined reference to 'msg'的编译错误:
269+
270+
// source1.cpp
271+
extern void sayHello();
272+
static const char* msg = "Hello World!\n";
273+
int main()
274+
{
275+
sayHello();
276+
return 0;
277+
}

0 commit comments

Comments
 (0)