Let's assume I have 2 functions other than the main(), respectively func1() and func2(). Is it possible for me to call func1() in func(2) without declaring it first? Or should I use a pointer to the other function and pass it as an argument? Thanks in advance.
_"Is it possible for me to call func1() in func(2) without declaring it first?"_
It depends on compiler, but generally this will not work. (see exclusion example at bottom of answer.)
Some scenarios that illustrate:
Scenario 1: Normally will not work as function is being referenced before being declared:
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Results:
9, 15 error: implicit declaration of function 'func1' is invalid
in C99. Make sure that you include the function prototype.
Scenario 2: As all required definitions occur in order, this will compile and run without issue:
char func1(void)
{
return 1;
}
char func2(void)
{
return func1();
}
int main(void)
{
char ret = func1();
ret = func2();
return 0;
}
Results:
Compiles and runs with no problem because both functions are defined before being called (both func2() called from main() and func1() called from func1)
Scenario 3: The best way is always to pre-declare functions using prototypes either in same file before functions are called or in a header file that is #included in any source file that uses them. This clears up any potential problems, especially for those that inherit the code for maintenance:
int func1(void);
int func2(void);
int main(void)
{
int ret = func1();
return 0;
}
int func1(void)
{
return 1;
}
int func2(void)
{
return func1();
}
Regarding your comment:
"...a statement in my book caused confusion, I thought it might be related to a difference of the version of the C compiler in the book and I am using."
Could be: Per comment below, pre-standard C function definitions are supported by some modern compilers (eg gcc) thus would compile scenarios 1 & 2 without issue if functions complied with the default function definition; eg:
int func1(void)
int func2(void)
Here is how you do it:
void func2(int code); // forward declaration
void func1(const char* str)
{
func2(str[0]); // a call to a declared function
}
void func2(int code) // the callee
{
printf("code: %d\n", code);
}
Related
I'm trying to call other adjacent functions (delay() and delay_ex()) from a function (bitcheck()) as shown below and as expected, the compiler has thrown an error that delay() and delay_ex() functions weren't declared in the scope and I understood that we can't call functions other than from the main. So, I declared these delay() and delay_ex() functions in a header file and called from this program by including the header file, it worked well. So, is there any other such way to make this work?
void bitcheck()
{
int i;
for(i=0;i<NELEMS(array); i++)
{
delay();
AP_CMU->DIVIDER = freq_def[0];
encryption(array,i);
delay();
// LCD_DisplayUint32(i,0,array[i]);
AP_CMU->DIVIDER = freq_def[6];
delay_ex(10);
decryption(intr_array,i);
delay_ex(10);
// LCD_DisplayUint32(i,10,array[i]);
}
}
void delay()
{
int i;
for (i = 0; i < 100000; i++) {
__NOP();
}
}
void delay_ex(int j)
{
for(int s=0; s < j; s++)
{
for ( int i = 0; i < 10000; i++) {
__NOP();
}
}
}
You can write your functions above the code that calls them like:
void foo() {
}
void bar() {
}
int main () {
foo();
bar();
}
You can also forward declare functions like:
void foo();
void bar();
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
Or you can put them in a header file and include it
file.h:
void foo();
void bar();
file.c:
#include "file.h"
int main () {
foo();
bar();
}
void foo() {
}
void bar() {
}
The compiler works in a single pass, as such when bitcheck() is parsed, the signatures of delay() and delay_ex() are not known, so the compiler cannot verify the call is type-correct.
The rule is declare or define before use; there are two possible solutions:
Define bitcheck() after the definition of delay() and delay_ex()
Forward-declare delay() and delay_ex().
By declaring the functions in a header and including it before defining bitcheck(), you used the second of these solutions, but use of an include file was not essential - #include does noting more than insert the file content into the translation-unit prior to compilation. This is useful when the symbols will be called from a different translation-unit than that in which they are defined; if that is not intended the declarations may be written directly rather then #include'd, and should also be declared static to avoid external-linkage and potential name clashes with other translation-units.
You need to define delay and delay_ex before bitcheck. Simply moving those two functions above bitcheck should suffice.
I want to call function according to func_name string.
My code is here below:
#define MAKE_FUNCNAME func_name##hello
void call_func(void* (*func)(void))
{
func();
}
void *print_hello(void)
{
printf("print_hello called\n");
}
int main(void)
{
char func_name[30] = "print_";
call_func(MAKE_FUNCNAME);
return 0;
}
But this code doesn't work. I want code to work like call_func(print_hello). But preprocessor treated my code like call_func("print_hello"). How to use macro in C to make my exception? Or is it not possible using C?
Then problem with your code is that the value of func_name is only known at run-time.
You can however to it like this:
#define MAKE_FUNCNAME(FUNCNAME) FUNCNAME##hello
void call_func(void* (*func)(void))
{
func();
}
void *print_hello(void)
{
printf("print_hello called\n");
}
int main(void)
{
call_func(MAKE_FUNCNAME(print_));
return 0;
}
But it is not possible to use a string value within macro parameters like in your code snippet.
If you want to get call functions with their names using string values you can use a table to store function pointer with function names like this:
struct {
const char *name;
void (*ptr)(void);
};
You can use an array of this structure to find out the function pointer at run-time using a string value. This is the most common solution to using run-time strings to call functions using their names.
You can't do that. The value of func_name is known at run-time (even though it is a const char *), while you want to determine what to call at precompile-time. You should turn your cpp macro into something different (such as an if/switch statement or using an indirection).
Maybe you could have a look to dlsym().
Not sure I really understand the question, but if you want to "build" the function name at runtime and then call the corresponding function, it should be possible with dlsym()
/* compile with: gcc example.c -ldl -rdynamic */
#include <dlfcn.h>
#include <stdio.h>
int print_hello(void)
{
return printf("hello\n");
}
int main(int argc, char *argv[])
{
const char *name = "print_hello";
if (argc == 42)
print_hello(); /* for compiler not to remove print_hello at
* compile time optimisation in this example*/
void *handle = dlopen(NULL /* self */, RTLD_NOW);
int (*f)(void) = dlsym(handle, name);
f();
return dlclose(handle);
}
i tested this simple program of function pointer.
#include <stdio.h>
#include <conio.h>
void ptr();
void fun()
{
printf("fun() is called\n");
}
void ptr()
{
printf("ptr() is called\n");
}
int main()
{
void(*ptr)();
ptr=fun;
ptr(); // Why it works fine?
//(ptr)();
void(*a)()=fun;
(*a)();
_getch();
return 0;
}
output:
fun() is called
fun() is called
I have a question that why the function call statement
ptr();
won't call user defined function ptr(), but calls fun() function?
Why parentheses around ptr isn't necessary?
What changes my program will require so my program displays output as following.
ptr() is called
fun() is called
When you define a local variable ptr inside main, it shadows the same name function ptr which is global. So when you call ptr(), it's the local function pointer ptr that is called.
To make the function ptr being called, you need to make sure the local variable ptr is out of scope, as this artificial example:
int main()
{
{
void(*ptr)();
ptr=fun;
}
ptr();
}
It is an application of the usual scoping rules; local variables hide global variables of the same name.
Or, more accurately, variables defined in an inner scope hide variables of the same name in any outer scopes.
And scopes are basically controlled by sets of braces around blocks of statements (simplifying a bit).
You can get GCC to warn you about such problems with -Wshadow.
The other part of the issue is that you can call functions via a pointer to function in (at least) two ways:
(*ptr_to_function)(); // Pre-standard notation
ptr_to_function(); // Notation allowed by standard C
So the call ptr(); is identical to (*ptr)(); in your program.
What changes does my program require to display:
ptr() is called
fun() is called
The simplest change is to remove the line void (*ptr)() = fun;.
You could also do something like:
#include <stdio.h>
void fun(void)
{
printf("fun() is called\n");
}
void ptr(void)
{
printf("ptr() is called\n");
}
int main(void)
{
void (*xyz)(void) = ptr;
void (*ptr)(void) = fun;
xyz();
ptr();
return 0;
}
In a system with a precompiled binary similar to this:
int foo(int bar) {
// do something wrong
return ...;
}
Is there a method I can use to, during runtime, change the effect of calling that function to:
int foo(int bar) {
return fixedFoo(bar);
}
Without changing other binaries? I.e. is there some memory hackery I can do to change the functionality of calling foo?
Sadly I cannot pre-patch the binary since the correct behaviour of foo is dependent on the result of runtime startup.
If you have access to the source code, you could make foo a function pointer and then set foo to the routine you want after "runtime startup".
#include <stdio.h>
int (*foo)(int);
int bar(int a) { printf("bar %d\n", a); return 0; }
int baz(int a) { printf("baz %d\n", a); return 0; }
int main(void) {
// do start up here
foo = bar;
foo(23);
return 0;
}
prints
bar 23
I am having problem with importing external function to a main c file.
Here is my minimal code:
/* main.c */
#include<stdio.h>
extern int func()
int main(){
extern int func();
}
/*external file with one function that I want to
import*/
#include<stdio.h>
int func(){
printf("Hello World Again\n");
}
I compile and run like this - gcc main.c and then ./a.out but nothing is happening.
Any idea ?
You have to compile the file containing func also
gcc -Wall main.c external_file.c
(Note that the -Wall in the compiler command isn't absolutely necessary but is very good practice)
As noted by others, you also need to fix your code to call func rather than just re-declaring it.
Because you only declared the function, You never called it!
extern int func();
Declares a function. To call it you must have:
int main()
{
func();
}
You are just declaring again in main function..
you need to call the function to work..#include
extern int func()
int main(){
func();
}
/*external file with one function that I want to
import*/
#include<stdio.h>
int func(){
printf("Hello World Again\n");
}
Edits: question has changed.
extern is only used for external variables. You just need a prototype for the function.
#include <stdio.h>
void func(void); /* <-- prototype */
int main(int argc, char * argv[])
{
func();
return 0;
}
void func(void){
printf("Hello World Again\n");
}
Notice a few things. A prototype of int func() means no parameter checking in C - this is different to C++. Also, you are not returning anything from the function, so I replace it with void func(void)