what I'm trying to do is not ideal, but I want to know if there's a way to tackle the below problem.
So I have 2 different c files.
first.c
#include <stdio.h>
#include <second.h>
void hello()
{
printf("world()!\n");
}
second.c
#include <stdio.h>
void code()
{
//some code that can call the hello() function in the first.c file.
}
So the first.c code has the second.h header file included in the code, but the second.c doesn't have the first.h header file included in the code. Are there any ways to run the "hello()" function in the first.c by second.c with the given condition?
CodePudding user response:
Yes, you can have first.c
include second.h
and second.c
include first.h
. Note this is not circular, because you aren't including the headers from each other.
CodePudding user response:
Declare it first:
#include <stdio.h>
void hello();
void code()
{
hello();
}
CodePudding user response:
Two solutions:
1 - Use a very, very old C compiler that did not perform function signature checking.
2 - Use a 'helper function' in another .c
that has visibility of what you want to run. Call the function indirectly
...
// first.h
void hello();
// first.c
#include <stdio.h>
void hello()
{
printf("world()!\n");
}
// third.h
typedef void(*func_t)();
func_t get_it();
// third.c
#include "first.h"
#include "third.h"
func_t get_it() {
return &hello;
}
// second.c
#include <stdio.h>
#include "third.h"
int main() {
printf( "Hello " );
(*get_it())(); // call 'hello' from first.c
return 0;
}
Output:
Hello world()!