how to use static function defined in one file in another file is that impposiible in 'c '

R

rashmi

how to use static function defined in one file in another file is that
impposiible in 'c '
 
M

Martin Ambuhl

rashmi said:
how to use static function defined in one file in another file is that
impposiible in 'c '

/* file b.c */
/* hidden function */
static int local_foo(int x) {
return x*x;
}

/* function with external linkage */
int foo(int x) {
return local_foo(x);
}

/* function pointer with external linkage */
int (*foop)(int) = local_foo;

/* file a.c */
#include <stdio.h>
int foo(int);
int (*foop)(int);

int main(void)
{
int x = 2;
printf("foo(%d) = ",x);
printf("%d\b", x = foo(x));
printf("foop(%d) = ",x);
printf("%d\b", x = foop(x));
return 0;
}

[output]
foo(2) = 4
foop(4) = 16
 
C

CBFalconer

rashmi said:
how to use static function defined in one file in another file is
that impposiible in 'c '

You can only do that by passing a pointer to the function to some
other function. Look at the way my hashlib is configured via the
hshinit function. The function pointers passed may be static in
the calling module, and in fact often are. See:

<http://cbfalconer.home.att.net/download/>

Static, when applied to a function, means that the name is not
externally available for linking, and thus will not create
namespace conflicts. The code itself remains accessible.
 
K

Keith Thompson

rashmi said:
how to use static function defined in one file in another file is that
impposiible in 'c '

If you can obtain a pointer to the function, you can call it through
the pointer. Or if you really mean "file" rather than "translation
unit", you can #include the file containing the function definition
(which is almost certainly not what you're asking for and not a good
idea).

But basically the point of declaring a function static is so that it
*can't* be called from outside the translation unit that defines it.

Why do you want to do this?
 
M

msigwald

rashmi said:
how to use static function defined in one file in another file is that
impposiible in 'c '

You could always have a wrapper function in the same file containing
the static function. This function would be of external linkage and
would invoke the static function internally.
So, you would have two functions in this file:
static my_static_fun{};
and the wrapper function
my_static wrapper
{
my_static_fun();
};

Then, you just include a header file containing the prototype of this
function in the other file from which you want accs to the static fun.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top