1

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?

  • Please pick one programming language. – Antti Haapala -- Слава Україні Jan 31 '20 at 13:36
  • Do you mean "compile time" or "link time"? By "exist", do you mean "defined" or "declared"? Compile time can detect declared but it has no insight into whether it is defined, because whether a function is defined is determined by what you pass to the linker. – Raymond Chen Jan 31 '20 at 13:40
  • You don't have a static function, you have a global function with external linkage. Since C++ operates on translation unit level, there is no way to determine anything outside a given translation unit. What you want is impossible. – rustyx Jan 31 '20 at 13:43
  • Note the C++ code won't work even if the function is defined unless there's a declaration `extern "C" void Foo();`. Remember that in C, `void Foo();` and `void Foo(void);` are not the same! – aschepler Jan 31 '20 at 13:44
  • @RaymondChen I meant "declared", I edited my question to make it more understandable. – Parminder Singh Jan 31 '20 at 13:51
  • Does the `function.c` file have an associated header file such as `function.h` that you can `#include`? – Andrew Henle Jan 31 '20 at 14:07
  • It seems unwise to have this code's functionality depend on whether or not you remembered to `#include` the header that declares `Foo()`. That's the sort of thing you want the compiler to remind you about, not gloss over. What is the real problem here? – JaMiT Jan 31 '20 at 15:55

1 Answers1

2

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.

Ctx
  • 18,090
  • 24
  • 36
  • 51