473,734 Members | 2,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

accessing static variables from outside their function

Does anyone know of a way of accessing and modifying variables declared
static within a function from outside that function? Please no
homilies on why it's bad practice: the context is very particular and
involves automatically generated code. I know several other ways of
attacking my problem, but this would be the cleanest if it could be made
to work.

A little more context. I use C as the output of a code generating
system which can, and frequently does, output very many functions that have a
consistent set of declarations, including variable names, at the top.
One of these is typically a static integer, call it "done", which causes
an immediate return if it has been set to 1, otherwise the function
proceeds. I take it that this is a well-known, trivial and banal piece
of code for permitting a function to run just once.

Now, however, circumstances have arisen where it might be desirable to
be able to reset this flag from outside the function in which it is
declared. Compiling, as I do, using gcc with -rdynamic, I am routinely
able, using dlopen and dlsym, to find the address of a function by name.
I had (naively) imagined that dladdr() would allow me to get the addresses
of symbols declared static within functions, but as I understand it
dladdr() only accesses global symbols. So what I am looking for is a
method for finding the address of a static integer variable called
"done" declared within "function00 1", as opposed to all other static
integer variables called "done" declared within all the many other
similar functions, in such a way that I can change its value - so
just getting a copy won't do.

I am asking in this group rather than in a gcc specific place because in
principle this is not a gcc-specific issue and my software compiles
using other compilers with comparable tricks. The more generic and
surgical a solution the better. But my functions may have a variable and
unpredictable number of arguments.

Pointers, RTFMs with page references and philosophical musings all
welcome. But an illustrative code fragment would be perfect.

--
Steve Blinkhorn <st***@prd.co.u k>
May 10 '06 #1
12 11716
Steve Blinkhorn said:
Does anyone know of a way of accessing and modifying variables declared
static within a function from outside that function?


Eeeeewwww. :-)

One obvious way - you could hack up a file scope pointer, and initialise it
first time in, to point at the static object.
int *flagptr;

void foo(void) /* I'm guessing your interface is written in stone! */
{
static int flag = 0; /* this is the bunny */

if(flagptr == NULL)
{
flagptr = &flag;
}

/* whatever floats your boat... */

return;
}

/* a different source file */

extern int *flagptr;

void bar(void)
{
foo();
*flagptr = 1; /* hack, chop, maim */
foo();
}
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
May 10 '06 #2
Steve Blinkhorn wrote:
Does anyone know of a way of accessing and modifying variables declared
static within a function from outside that function?
...
A little more context. I use C as the output of a code generating
system which can, and frequently does, output very many functions that have a
consistent set of declarations, including variable names, at the top.
One of these is typically a static integer, call it "done", which causes
an immediate return if it has been set to 1, otherwise the function
proceeds. I take it that this is a well-known, trivial and banal piece
of code for permitting a function to run just once.

Now, however, circumstances have arisen where it might be desirable to
be able to reset this flag from outside the function in which it is
declared.

I am asking in this group rather than in a gcc specific place because in
principle this is not a gcc-specific issue and my software compiles
using other compilers with comparable tricks. The more generic and
surgical a solution the better. But my functions may have a variable and
unpredictabl e number of arguments.

Pointers, RTFMs with page references and philosophical musings all
welcome. But an illustrative code fragment would be perfect.


Two ideas:

(a) (Compiler specific) Check the sources of a debugger that works
with your toolchain, to see how to map a variable name into its run
time address.

(b) Change the problem definition. Write a filter (awk, perl, etc.) to
convert this:

(file xxx.c)

... yyy(...)
{
static int done;
/* the rest goes here */
}

into this:

int xxx_yyy_done;

... yyy(...)
{
/* the rest goes here */
}

(b and 1/2) Modify the "code generating system" to directly produce
form (b)

May 10 '06 #3
In article <12************ *@corp.supernew s.com>,
Steve Blinkhorn <st***@newsole. prd.co.uk> wrote:
Does anyone know of a way of accessing and modifying variables declared
static within a function from outside that function? Now, however, circumstances have arisen where it might be desirable to
be able to reset this flag from outside the function in which it is
declared. Compiling, as I do, using gcc with -rdynamic, I am routinely
able, using dlopen and dlsym, to find the address of a function by name. I am asking in this group rather than in a gcc specific place because in
principle this is not a gcc-specific issue and my software compiles
using other compilers with comparable tricks.


No, in principle it *is* gcc-specific -- or at least OS specific,
if the OS dictates that all executables must use the same debugger
table format.

On some systems, gcc emits debugging table entries that are
in executable sections not known to the OS-supplied debugger (and hence
are ignored by the system debugger.)

There is no requirement in the C standard that a symbol table of any
sort must be kept, beyond that which is implied by the discussions
of "external linkage" (which does not imply that a "linker" must
exist: it would be valid for a compiler to require that all sources
be named on the same command line, and for the compiler to do everything
in-memory.)

Anything further than "different executable formats may exist" is
not considered to be on topic for comp.lang.c
--
"law -- it's a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)
May 10 '06 #4
Richard Heathfield <in*****@invali d.invalid> wrote:
: Steve Blinkhorn said:

: > Does anyone know of a way of accessing and modifying variables declared
: > static within a function from outside that function?

: Eeeeewwww. :-)

Absolutely, I do so agree ;-)

: One obvious way - you could hack up a file scope pointer, and initialise it
: first time in, to point at the static object.
Thanks for the amazingly fast response, but I don't think this one is a
runner, unless I misunderstand. Let me explain a little more. My
people write scripts that get translated into C. Their scripting may
generate (potentially) hundreds of functions (they don't actually
understand that that is what happens), though they do know that they
have generated a name for an object. So they need to reference their
object by its name to tell it to respond again. Imagine a function
called retrigger(objec tname) as the natural thing to do. If I
understand you correctly, you are suggesting that for each function we
generate a variable in the global namespace that allows us to access the
static flag inside the function?

I'm sure this would actually work in that it would achieve the
objective, but it would involve a naming scheme for the global variables,
which might involve more trouble than some of the other methods I have
considered (which might require doing something with the function
interface).

This one is a bit like having a hole in your tooth, sort of exquisitely
unpleasant, isn't it?

--
Steve Blinkhorn <st***@prd.co.u k>
May 10 '06 #5
try Lisp or Scheme.

these languages are first class and functions can be returned and
stored.

C is 2nd class language.

May 10 '06 #6
In article <11************ **********@i39g 2000cwa.googleg roups.com>,
dick <di***********@ hotmail.com> wrote:
try Lisp or Scheme. these languages are first class and functions can be returned and
stored. C is 2nd class language.


Could you give a formal definition by which we can objectively
decide whether a given programming language is "first class",
"2nd class", or some other class?

Languages themselves are seldom given class numbers. "first class"
is used in computer science to refer to *types of objects*,
not to the languages themselves. As phrased in a paper on DBPL:
http://www.sts.tu-harburg.de/papers/198x/MaSc89.pdf

Values of all DBPL types are first class language objects: They
can be named, denoted by expressions, stored in (persistent) variables
and passed as value and variable parameters.

In the C language, functions are not first class language objects
in that functions cannot be stored, dynamically created, nor passed
(only function -pointers-). That doesn't mean that the C -language-
itself is not first class.
Furthermore, languages in which functions can be returned and stored
do not necessarily allow examination or manipulation of the internal
details and values of the functions.
For an example of the complexities involved:

The Maple programming language (Maplesoft) allows procedures to
be created, stored, and passed. The names of parameters and local
variables and explicitly-declared global variables used by the
procedures may be examined, and the values stored in its
"remember" table may be examined and manipulated. There is no
simple way to examine the code of the procedure (there are
multilevel complex ways), but a new procedure can be easily produced
by "substituti ng" something for a name that one happens to know
appears inside the procedure (e.g., one could change a call to
sin into one to cos). Maple procedures may be "closures" -- they
can use local variables from the scope they were defined in
[even after that defining procedure has exitted], and the names
of those symbols can be examined and their values manipulated.
BUT -- when one is doing the "substituti on" operation, Maple does
not notice that one is attempting to bind a enclosure variable
from the current scope into a part of the procedure that did not
originally use an enclosure variable. There are subtle cheats that
one can use to accomplish this if the procedure originally had
at least one enclosure variable reference to start with, but not
if the procedure did not originally have any enclosure references at all.

So is Maple a "first class language" or not? Where does the ability to
inject brand new enclosure information fit into your decision as exactly
what class a language is? If Maple is not "first class" because it
doesn't allow this subtle feature, and yet allows functions to be
stored and passed, and you have defined C to be 2nd class when it
doesn't allow functions to be manipulated in any of those ways, then
where does Maple sit? Is it a "One and six thirty-sevenths class language" ?
--
Programming is what happens while you're busy making other plans.
May 10 '06 #7
Steve Blinkhorn wrote:
Richard Heathfield <in*****@invali d.invalid> wrote:
int *flagptr; I'm sure this would actually work in that it would achieve the
objective,
but it would involve a naming scheme for the global variables,
which might involve more trouble than some of the other methods I have
considered (which might require doing something with the function
interface).

"done" declared within "function00 1"


int *flagptr001;

--
pete
May 10 '06 #8
Steve Blinkhorn schrieb:
Does anyone know of a way of accessing and modifying variables declared
static within a function from outside that function? Please no
homilies on why it's bad practice: the context is very particular and
involves automatically generated code. I know several other ways of
attacking my problem, but this would be the cleanest if it could be made
to work.


As you know it is not advisable, here is a method which may help.

enum {
E_STATE_FOO,
....
E_STATE_QUUUUUU UUUUUUUUUUUX,
E_NUM_STATES
};
int *gimmeStatus (unsigned int index)
{
static int status_table[E_NUM_STATES];
static int scratch;

if (index < E_NUM_STATES)
return &status_tabl e[index];
else {
/* Do some error handling if necessary or insert
** assert(0);
** for your debug mode or whatever...
*/
return &scratch;
}
}

void example (int seventeen, int four) {
static int *pState = 0;

if (!pState) {
pState = gimmeStatus(E_S TATE_FORTY_TWO) ;
*pState = MY_EXAMPLE_STAR T_STATUS;
}

....
}

void externModificat ion (void)
{
*gimmeStatus(E_ STATE_FORTY_TWO ) = 42;
}
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
May 10 '06 #9
Steve Blinkhorn wrote:

Does anyone know of a way of accessing and modifying variables
declared static within a function from outside that function?
Please no homilies on why it's bad practice: the context is very
particular and involves automatically generated code. I know
several other ways of attacking my problem, but this would be
the cleanest if it could be made to work.


int *foo(int param) {

static int foostate;

....
return &foostate;
} /* foo */

.....

int *p

...
do {
....
while (somethingelse) {
p = foo(...);
...
}
if (restart) *p = 0;
} while (!restart);

Now write your own homilies here and swear not to do it again.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 11 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
15261
by: Leigh Riley | last post by:
Hi, Can someone tell me if the following is possible? I have a file containing some STATIC variables, and some functions e.g. ------------------------------------------------- $ARCHIVE_INPUT_FILES = false; $ARCHIVE_OUTPUT_FILES = false; $ARCHIVE_CONFIG_FILES = false; $HTML_BODY_BACKGROUND = "gfx/gradient.gif";
6
3163
by: pembed2003 | last post by:
Hi all, I am reading the book "C++ How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope function-prototype scope I think(might be wrong):
2
1874
by: katekukku | last post by:
HI, Could anyone please tell me what are static variables and what exactly are there features. I am a little bit confused. Thank You
3
3934
by: Datta Patil | last post by:
Hi , #include<stdio.h> func(static int k) /* point2 : why this is not giving error */ { int i = 10 ; // static int j = &i ; /* point 1: this will give compile time error */ return k; } /* in above case where is variable k and j mapped in memory layout ? */
12
1916
by: codefixer | last post by:
Hello: I am trying to understand the use of static in this program. http://nanocrew.net/sw/nscdec.c for "inverse" matrix. What difference would it make if it were not static and just "const unsigned char inverse" in global space which it already is ? Thanks.
11
3841
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you experts. I would like to produce Javascript classes that can be "subclassed" with certain behaviors defined at subclass time. There are plenty of ways to do this through prototyping and other techniques, but these behaviors need to be static and...
18
33891
by: Jack | last post by:
Thanks.
55
6235
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
2
2554
by: Licheng Fang | last post by:
On Apr 14 2003, 10:30 pm, Alex Martelli <al...@aleax.itwrote: Sorry to dig up this old thread, but I would like to know what's the rationale is. Why can't a nested function rebind a variable of an outer function? I was trying to write a function that creates another function and returns it when I came across this problem. These two solutions have a difference:
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.