rairairaira
rairairaira

Reputation: 1

Is there a way to run the function without directly calling it?

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?

Upvotes: 0

Views: 74

Answers (3)

FelipeC
FelipeC

Reputation: 9488

Declare it first:

#include <stdio.h>

void hello();

void code()
{
    hello();
}

Upvotes: 1

Fe2O3
Fe2O3

Reputation: 8344

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()!

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249093

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.

Upvotes: 2

Related Questions