C/C++ÖÐStaticµÄ×÷ÓÃÏêÊö
C/C++ÖÐStaticµÄ×÷ÓÃÏêÊö
http://developer.51cto.com 2008-12-29 09:52 ØýÃû ÖйúITʵÑéÊÒ ÎÒÒªÆÀÂÛ(0)
CÓïÑÔÖУ¬staticµÄ×ÖÃæÒâ˼ºÜÈÝÒ×°ÑÎÒÃǵ¼ÈëÆç;¡£±¾ÎĽ«¶ÔC/C++ÖÐStatic½øÐÐÏêÊö¡£
1.ÏÈÀ´½éÉÜËüµÄµÚÒ»ÌõÒ²ÊÇ×îÖØÒªµÄÒ»Ìõ£ºÒþ²Ø¡£
µ±ÎÒÃÇͬʱ±àÒë¶à¸öÎļþʱ£¬ËùÓÐδ¼Óstaticǰ׺µÄÈ«¾Ö±äÁ¿ºÍº¯Êý¶¼¾ßÓÐÈ«¾Ö¿É¼ûÐÔ¡£ÎªÀí½âÕâ¾ä»°£¬ÎÒ¾ÙÀýÀ´ËµÃ÷¡£ÎÒÃÇҪͬʱ±àÒëÁ½¸öÔ´Îļþ£¬Ò»¸öÊÇa.c£¬ÁíÒ»¸öÊÇmain.c.
ÏÂÃæÊÇa.cµÄÄÚÈÝ£º
char a = 'A'; // global variable
void msg()
{
printf("Hello\n");
}
ÏÂÃæÊÇmain.cµÄÄÚÈÝ£º
int main(void)
{
extern char a; // extern variable must be declared before use
printf("%c ", a);
(void)msg();
return 0;
}
³ÌÐòµÄÔËÐнá¹ûÊÇ£º
A Hello
Äã¿ÉÄÜ»áÎÊ£ºÎªÊ²Ã´ÔÚa.cÖж¨ÒåµÄÈ«¾Ö±äÁ¿aºÍº¯ÊýmsgÄÜÔÚmain.cÖÐʹÓã¿Ç°Ãæ˵¹ý£¬ËùÓÐδ¼Óstaticǰ׺µÄÈ«¾Ö±äÁ¿ºÍº¯Êý¶¼¾ßÓÐÈ«¾Ö¿É¼ûÐÔ£¬ÆäËüµÄÔ´ÎļþÒ²ÄÜ·ÃÎÊ¡£´ËÀýÖУ¬aÊÇÈ«¾Ö±äÁ¿£¬msgÊǺ¯Êý£¬²¢ÇÒ¶¼Ã»ÓмÓstaticǰ׺£¬Òò´Ë¶ÔÓÚÁíÍâµÄÔ´Îļþmain.cÊǿɼûµÄ¡£
Èç¹û¼ÓÁËstatic£¬¾Í»á¶ÔÆäËüÔ´ÎļþÒþ²Ø¡£ÀýÈçÔÚaºÍmsgµÄ¶¨ÒåÇ°¼ÓÉÏstatic£¬main.c¾Í¿´²»µ½ËüÃÇÁË¡£ÀûÓÃÕâÒ»ÌØÐÔ¿ÉÒÔÔÚ²»Í¬µÄÎļþÖж¨ÒåͬÃûº¯ÊýºÍͬÃû±äÁ¿£¬¶ø²»±Øµ£ÐÄÃüÃû³åÍ»¡£Static¿ÉÒÔÓÃ×÷º¯ÊýºÍ±äÁ¿µÄǰ׺£¬¶ÔÓÚº¯ÊýÀ´½²£¬staticµÄ×÷ÓýöÏÞÓÚÒþ²Ø£¬¶ø¶ÔÓÚ±äÁ¿£¬static»¹ÓÐÏÂÃæÁ½¸ö×÷Óá£
2.staticµÄµÚ¶þ¸ö×÷ÓÃÊDZ£³Ö±äÁ¿ÄÚÈݵij־á£
´æ´¢ÔÚ¾²Ì¬Êý¾ÝÇøµÄ±äÁ¿»áÔÚ³ÌÐò¸Õ¿ªÊ¼ÔËÐÐʱ¾ÍÍê³É³õʼ»¯£¬Ò²ÊÇΨһµÄÒ»´Î³õʼ»¯¡£¹²ÓÐÁ½ÖÖ±äÁ¿´æ´¢ÔÚ¾²Ì¬´æ´¢Çø£ºÈ«¾Ö±äÁ¿ºÍstatic±äÁ¿£¬Ö»²»¹ýºÍÈ«¾Ö±äÁ¿±ÈÆðÀ´£¬static¿ÉÒÔ¿ØÖƱäÁ¿µÄ¿É¼û·¶Î§£¬Ëµµ½µ×static»¹ÊÇÓÃÀ´Òþ²ØµÄ¡£ËäÈ»ÕâÖÖÓ÷¨²»³£¼û£¬µ«ÎÒ»¹ÊǾÙÒ»¸öÀý×Ó¡£
#include £¼stdio.h£¾
int fun(void){
static int count = 10; // ÊÂʵÉϴ˸³ÖµÓï¾ä´ÓÀ´Ã»ÓÐÖ´Ðйý
return count--;
}
int count = 1;
int main(void)
{
printf("global\t\tlocal static\n");
for(; count £¼= 10; ++count)
printf("%d\t\t%d\n", count, fun());
return 0;
}
³ÌÐòµÄÔËÐнá¹ûÊÇ£º
global local static
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2
10 1
3.staticµÄµÚÈý¸ö×÷ÓÃÊ
Ïà¹ØÎĵµ£º
I2CÊÇPhillips¿ª·¢µÄ2ÏߵĴ®ÐÐ×ÜÏßÐÒ顣ͨ³£Ó¦ÓÃÔÚǶÈëʽϵͳÖÐÈò»Í¬µÄ×é¼þͨÐÅ£¬PCÖ÷°å¿ÉÒÔͨ¹ýI2CÀ´Ó벻ͬµÄ´«¸ÐÆ÷ͨÐÅ¡£ÕâЩ´«¸ÐÆ÷ͨ³£±¨¸æ·çÉÈËٶȣ¬´¦ÀíÆ÷ζȺÍÕû¸öÓ²¼þϵͳµÄÐÅÏ¢£¬Õâ¸öÐÒéÒ²¿ÉÒÔÓÃÔÚRAM chipsÉÏ£¬Ïò²Ù×÷ϵͳÌṩDIMMµÄÐÅÏ¢¡£
ÔÚ2.0ʱI2CµÄkernelÔ´Âë²»ÔÚÄÚºËÀïµÄ£¬2.4Äں˰üÀ¨ÁËÒ»µã¶ÔI2CµÄÖ§³Ö ......
1.Òª½âÎöµÄXMLÎļþÈçÏ£º
<?xml version="1.0" encoding="GB2312"?>
<?xml-stylesheet href="student.xsl" type="text/xsl"?>
<StudentInfo>
<student>
<name>´ïÄÚ</name>
<sex>ÄÐ</sex>
<lesson>
  ......
ÎÄÕÂ×÷ÕߣºSlyar
ÏÈ¿´Á½¸ö´úÂ룬µÚÒ»¸öÊÇC³ÌÐò£¬µÚ¶þ¸öÊÇC++³ÌÐò£¬³ýÁËÍ·Îļþ²»Í¬ÒÔÍâÆäËûµÄ¶¼Ò»Ñù¡£
//demo.c
#include <stdio.h>
int foo();
int main()
{
int a;
foo(a);
return 0;
}
int foo(int a)
{
}//demo.cpp
#include <iostream>
int foo();
int main()
{
in ......
µÚ3Õ ÔõÑù²ÅÄܸßЧÂʲâÊÔ
3.1 ËÆÊǶø·ÇµÄ¸ßЧÂÊ
ÕâÒ»½Ú³ÎÇåһЩÁ÷ÐеÄÎó½â»òÎóµ¼£¬Ò»Ð©¿´ÆðÀ´ºÜ²»´íµÄ¸ßЧÂÊ£¬Êµ¼ÊÉÏÊÇËÆÊǶø·ÇµÄ¡£
È«×Ô¶¯Éú³ÉÓÃÀý
È«×Ô¶¯Éú³ÉÓÃÀýÊÇËùÓвâÊÔÈËÔ±µÄÆÚÅΣ¬ºÃÏûÏ¢ÊÇ£¬ÕâÊÇÒ»ÖÖ¼òµ¥µÄ¼¼Êõ£¬Ê®ÄêÇ°¾ÍÓÐÁË£¬»µÏûÏ¢ÊÇ£¬ÕâÖÖ¼¼Êõ×÷ÓúÜС¡£
......