我对程序有问题。我敢打赌,这与我使用静态这一事实有关。这是我的
static int cnt;
void f();
Run Code Online (Sandbox Code Playgroud)
我的main.c
#include <stdio.h>
#include "t.h"
void main()
{
cnt=0;
printf("before f : cnt=%d\n",cnt);
f();
printf("after f : cnt=%d\n",cnt);
}
Run Code Online (Sandbox Code Playgroud)
最后是我的朋友
#include "t.h"
void f()
{
cnt++;
}
Run Code Online (Sandbox Code Playgroud)
printf两次打印cnt = 0。我做cnt ++怎么可能?有任何想法吗?
提前致谢
在中C,static表示“模块本地”
请注意,这些#include语句只是将头文件粘贴到包含文件中。
因此,您将在不同的模块中创建两个不同的符号(可能具有相同的逻辑名称)。然后
f.c cnt是不同的cntmain.c
注意:
static中的C含义与其C++对应的含义不同。
并且因为C++是CCompatible,所以static在类外部具有与in相同的含义C
编辑:
在您的情况下,您不希望static您想要一个变量,但是我想您在链接器告诉您有关“歧义符号”时遇到了问题。
我建议extern在头文件中声明一个,然后在模块中声明实际的变量。
日
extern int cnt; //声明变量cnt
main.cpp
#包括
#include“ th”
int cnt = 0; // cnt的实际定义
无效main()
{
cnt = 0;
printf(“ f之前:cnt =%d \ n”,cnt);
F();
printf(“ f之后:cnt =%d \ n”,cnt);
}
cpp
#include“ th”
无效f()
{
cnt ++;
}