Chinaunix

标题: static全局变量问题,急 [打印本页]

作者: yqw1122    时间: 2012-06-15 09:15
标题: static全局变量问题,急
本帖最后由 yqw1122 于 2012-06-15 09:16 编辑

现在正在看开源代码pjsip,对其中的一段代码的使用有些不解。
一个c文件定义了static 全局变量
static struct{
.....
int x;
int y;
.....
}global;


在另一个c文件中,直接调用
eg. global.x

搜索了全部文件(包括.c和.h),只有这两个c文件中有global,而且%p打印出了两个文件中global的内存地址是相同。


这个很奇怪,我第一个看到这样用。但是我自己写了测试程序,编译通不过。

请指点,难道有编译选项??
作者: folklore    时间: 2012-06-15 09:23
you can't refer to a static variant in outside the declearing file.
try
struct{
.....
int x;
int y;
.....
}global;

作者: yqw1122    时间: 2012-06-15 09:31
回复 2# folklore

pjsip是很著名的开源项目,人家这么写的,完全可以编译!!
作者: Moon_Bird    时间: 2012-06-15 09:41
回复 3# yqw1122
这个 eg. global.x   eg是什么?


   
作者: yqw1122    时间: 2012-06-15 09:50
回复 4# Moon_Bird

“eg” =》例如:
   
作者: folklore    时间: 2012-06-15 09:51
回复 3# yqw1122


    no ,you can't
i think that may do it like that

// xxx.h
static struct{
   int x;
}global;

// xxx.cpp
#inlucde "xxx.h"   //notice this sentence, it means just clone all the the content of xxx.h to xxx.cpp withoud changed
...
global.x;



作者: yqw1122    时间: 2012-06-15 10:04
回复 6# folklore


    gobal static全局变量是在一个.c文件中定义的。在另外一个c文件中直接使用。没有任何相关的h文件包含
作者: chinafuck    时间: 2012-06-15 20:08
不懂不懂不懂不懂不懂不懂
作者: cokeboL    时间: 2012-06-15 21:40
有一个文件没参加编译。经常看到开源的里面,把整个项目代码加到SI中,然后一个东西一找定义,出来5、6个地方有定义。
作者: linccn    时间: 2012-06-16 21:20
本帖最后由 linccn 于 2012-06-16 21:33 编辑

回复 1# yqw1122


  首先
static struct{
.....
int x;
int y;
.....
}global;
这个是出现在.h文件中,你的描述有误。

另外,这样果然可以,
  1. /× global.c ×/
  2. static struct {
  3.         int x;
  4.         int y;
  5. } global;
  6. int main()
  7. {
  8.         global.x = 10;
  9.         return 0;
  10. }
复制代码

作者: x5miao    时间: 2012-06-16 21:46
回复 1# yqw1122


    难道是传说中的#include “xx.c”??
作者: yqw1122    时间: 2012-06-18 08:57
回复 11# x5miao

不是的
   
作者: pandaiam    时间: 2012-06-18 11:52
给出文件和行数一起看看哪.
作者: L_kernel    时间: 2012-06-18 14:35
这毫无道理可言,一定是遗漏了某些东西。楼主给我们显示的只是代码片段。
作者: yqw1122    时间: 2012-06-18 16:02
本帖最后由 yqw1122 于 2012-06-18 16:07 编辑

有道理。
代码见附件

关联文件是:pjproject\pjsip\src\pjsua目录下的main.c 和misc.c。
main.c中Line:47

pjproject.tar.gz

593.04 KB, 下载次数: 4


作者: ualy123    时间: 2012-06-18 19:36
关键要看这几行
/*
* Auxiliary things are put in misc.c, so that this main.c file is more
* readable.
*/
#include "misc.c"

misc.c 不是单独参与编译的文件,它属于main.c的一部分,所以直接使用global变量是没问题的.
你看pjsip\build\Makefile ,根本就没有misc.c的影子.
作者: yqw1122    时间: 2012-06-18 19:53
回复 16# ualy123


    结贴,谢谢。
   




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2