I want to call a static function from another C file. But it always show \"function\" used but never defined
.
In ble.c
You get this message because you have declared the function to be static. So the implementation is only visible inside your .c file. Try removing the static from both your .h and .c, this should allow your function to be seen.
For restricting function access from other file, the keyword static is used
Access to static functions is restricted to the file except where they are declared.When we want to restrict access to functions from outer world, we have to make them static. If you want access functions from other file, then go for global function i.e non static functions.
Static function has internal linkage and it can be called only by functions written in the same file. However if you want to call static function from another file , we have a trick in C. Fallow the steps. 1. Create a function pointer globally in ble.c and define it.
(void)(*fn_ptr)();
static void bt_le_start_notification(void)
{
WPRINT_BT_APP_INFO(("bt_le_start_notification\n"));
fn_ptr=bt_le_start_notification;
}
in main.c extern the function pointer
#include "ble.h"
extern fn_ptr;
void application_start( void )
{
fn_ptr();
}
Hope it will be useful.
I agree with Frodo and ANBU.SANKAR Still if you want to call a static function outside the file you can use examples like below.
1.c
extern (*func)();
int main(){
(func)();
return 0;}
2.c
static void call1(){
printf("a \n");
}
(*func)() = &call1;
The keyword static
is often used to encapsulate the function in the source file where it is defined. So it is not meant to call a static
function from outside, an other c-file. An extern article[^] is explaining that topic pretty good I think.
Quote:
Static functions are much like private methods in Java or C++. A private method is a method which is only used by a class and can't be used outside of it. In C, we can declare a static function. A static function is a function which can only be used within the source file it is declared in.
So as a conclusion if you need to call the function from outside you do not define the function as static
.
The static function scope is file(i.e. translation unit) where it is defined.