From 2e087d1cee97c919b3e98ed9d5fd8de2f1312adb Mon Sep 17 00:00:00 2001 From: Francis <455954986@qq.com> Date: Sun, 10 Apr 2022 17:52:14 +0800 Subject: [PATCH] Update README.md --- basic_content/static/README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/basic_content/static/README.md b/basic_content/static/README.md index 669eda9f..001f2831 100644 --- a/basic_content/static/README.md +++ b/basic_content/static/README.md @@ -246,3 +246,32 @@ int main() Welcome to Apple! ``` +**限定访问范围** +static还有限定访问范围的作用(类似于匿名名字空间)。来自issue:https://github.com/Light-City/CPlusPlusThings/issues/142 + +// source1.cpp +extern void sayHello(); +const char* msg = "Hello World!\n"; +int main() +{ + sayHello(); + return 0; +} + +// source2.cpp +#include +extern char* msg; +void sayHello() +{ + printf("%s", msg); +} +g++对于上面两个代码文件是可以正常编译并且打印Hello World!,但如果给source1.cpp中的msg加上static,则会导致undefined reference to 'msg'的编译错误: + +// source1.cpp +extern void sayHello(); +static const char* msg = "Hello World!\n"; +int main() +{ + sayHello(); + return 0; +}