简体   繁体   English

从C中的另一个文件更新静态全局变量

[英]Update static global variable from another file in c

Update static variable outside of the file without modifying the file in which the static variable is declared in C lang. 在文件外部更新静态变量,而无需修改使用C lang声明了静态变量的文件。

Proj1 creates dll. Proj1创建dll。 Proj1 has abc.h file and it is defined as below : abc.h具有abc.h文件,其定义如下:

static BOOl stvar = False;//declared as global static variable

func1()
{
    stvar= TRUE;
}

func2()
{
    if(stvar == TRUE)
    {
        ....
    }
    else
    {
        func1();  //call to func1 sets STVAR = TRUE;
    }
}

Proj2 Creates exe. Proj2创建exe。 It has cprog1.c file. 它具有cprog1.c文件。 cprog1.c file is defined as follows: cprog1.c文件的定义如下:

cprogfunc1()
{
    func2(); //call to func2 sets STVAR = TRUE;
}

cprogfunc2()
{
    stvar = FALSE;
    func2();
}

We are setting stvar to false in cprogfunc2() to make it execute else block in func2() of abc. 我们在cprogfunc2() stvar设置为false,以使其在abc的func2()中执行else块。 h file . h file But the value we set in cprogfunc2() under cprog1.c is not reflected in abc.h file. 但是,我们在cprogfunc2()下的cprog1.c cprogfunc2()设置的值未反映在abc.h文件中。 We are updating static variable outside its declaration because we cannot modify anything under proj1 . 我们正在声明之外更新静态变量,因为我们无法在proj1下进行任何修改。 So please suggest some ways to update static variable from cprog1.c file without modifying abc.h/Proj1 . 因此,请提出一些无需修改abc.h/Proj1 cprog1.c即可从cprog1.c文件更新静态变量的方法。 If that is not possible suggest any workaround. 如果无法解决,请提出任何解决方法。 Thanks. 谢谢。

Solutions already tried : 解决方案已经尝试过:

  1. Making stvar non static - not possible since we can not modify abc.h file stvar非静态-无法,因为我们无法修改abc.h文件
  2. Using pointers - did not work 使用指针-不起作用

By definition, stvar was made static in order to limit accessibility to it, meaning the ideal way to tinker with it from the outside is to create an API for it (or indeed make it global, not static). 根据定义,将stvar设为静态是为了限制对其的可访问性,这意味着从外部修改stvar的理想方法是为其创建一个API(或者实际上使其成为全局的,而不是静态的)。 Since editing Proj1 is out of the question, we are left with a bad situation. 由于无法编辑Proj1,所以我们的处境很糟。

What you could do is to reset Proj1's state by freeing the dll and loading it again, as mention here. 您可以做的是通过释放dll并再次加载它来重置Proj1的状态,如此处所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM