#include<stdio.h>staticvoiddisplayMessage(){printf("This is a static function.\n");}intmain(){displayMessage();// 调用静态函数return0;} 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 3.静态全局变量的例子: #include<stdio.h>staticintcount=
// 在文件作用域内声明的静态全局变量static int globalStaticVar = 10;int main() {// 可以访问静态全局变量 printf("Global static variable: %d\n", globalStaticVar);return 0;} 3.静态函数:使用'static'关键字声明的函数是静态函数。静态函数具有以下特性:· 可见性:静态函数的作用域限于声明它们的...
Inside a function: global variable but visible only within the function (C++) Inside a class: global variable but visible only to the class Now let's see what the C11 standard says regardingstaticandextern(emphasis mine): 6.2.2.3 If the declaration of a file scope identifier for an object ...
util_func(100); // 调用main.c中的static函数,编译报错 #endif } 当test_func中的if-0打开后,根据我们上面的理论分析,肯定是编译不过的,如下: test_static$ gcc -o test *.c /usr/bin/ld: /tmp/ccawkyDR.o: in functiontest_func': test.c:(.text+0xa): undefined reference tol_count' /usr...
以下是static的详细用法和作用: 1. 静态局部变量 当static关键字用于局部变量时,它会改变该变量的存储期,使其具有静态存储期。这意味着该变量在程序的整个运行期间都存在,但其作用域仍然限定在定义它的代码块内。 示例: #include <stdio.h> void function() { static int count = 0; // 静态局部变量 count...
在上述代码中,每次调用function时,count的值都会递增,因为它在函数调用之间保持其值。 2. 静态全局变量 当static用于修饰全局变量(即在所有函数外部的变量)时,它会将变量的作用域限制在定义它的文件内。这有助于避免不同文件中的同名全局变量之间的冲突。 file1.c: #include <stdio.h> static int globalVar =...
}inti =1;staticintj =2; 将两个文件一起编译 gcc test_static1.c test_static2.c -o test_static 编译器会提示: /tmp/ccuerF9V.o: In function `foo':test_static2.c:(.text+0x0): multiple definition of `foo'/tmp/cc9qncdw.o:test_static1.c:(.text+0x0): first defined here/tmp/ccu...
c语言static的作用和用法 一、作用 static关键字用于修饰变量和函数,用于控制变量或函数的作用域、存储方式以及生命周期。二、用法 1. 修饰全局变量或函数:使用static修饰全局变量或函数可以将其变为内部链接,从而只能在本文件内使用,不会被其他文件所引用。2. 修饰局部变量:使用static修饰局部变量可以使其在函数...
printf("Updated Value: %d\n", globalVar); // 输出 Updated Value: 15 return 0; } ``` 3. 静态函数: ```c #include <stdio.h> static void staticFunction() { printf("This is a static function.\n"); } int main() { staticFunction(); // 输出 This is a static function. return ...
staticFunction(); // 如果取消注释并尝试调用会导致链接错误 int main() { publicFunction(); // 正确:可以通过publicFunction间接调用staticFunction // staticFunction(); // 错误:staticFunction在file2.c中不可见 return 0; } ``` ### 总结 - `static`局部变量保持其值直到程序结束,但其作用域不变。