Parminder Singh
Parminder Singh

Reputation: 362

Checking if a static function exists at compile time

function.c (I can't edit this file)

#define FOO    1

#if FOO == 1
    void Foo() {}
#endif

cpp

class MyClass
{
#if FOO == 1
    void CppFoo()
    {
        Foo();
    }
#endif
}

I want to do the same thing, but without using the define TEST in the main.cpp file

What I want to do:

class MyClass
{
#if (extern "c" Foo() exist)
    void CppFoo()
    {
        Foo();
    }
#endif
}

The CppFoo() method will not have to be declared if the static function Foo() has not been declared.

How can I do this?

Upvotes: 1

Views: 583

Answers (1)

Ctx
Ctx

Reputation: 18420

You can use a weak attribute, for example:

file a.c:

#include <stdio.h>

int foo() __attribute__ ((weak));
int foo() {}

int main(int argc, char** argv)
{
    foo();
}

File b.c:

#include <stdio.h>

int foo () {
    printf("Hello Wurld!\n");
}

Now if you do not compile and link b.c, then the default (no-op) function foo() is called, otherwise the function foo() from b.c.

Upvotes: 2

Related Questions