0

I am trying to use weak function in a class in C++. Below is what I wrote:

#include <stdio.h>
#include <iostream>

class A {
    public:
    void func(int argc, char *argv[]) __attribute__((weak));
};

// optional definition:
#if 0
void A::func(int argc, char *argv[]) { 
    printf("In func()\n");
    for(int aa = 0; aa < argc; aa++){
        printf("arg %d = %s \n", aa, argv[aa]);
    }
}
#endif

int main(int argc, char *argv[]) {
    A a1;
    if (a1.func){ 
        a1.func(argc, argv); 
    } else {
        printf("func() not available\n");
    }
    return 0;
}

But this gives below compilation error:

main.cpp: In function ‘int main(int, char**)’:
main.cpp:21:16: error: cannot convert ‘A::func’ from type ‘void (A::)(int, char**)’ to type ‘bool’
     if (a1.func){
                ^

If I move the func() outside a class and use gcc instead of g++, it compiles fine and works as expected. Can someone please tell what's the problem. Basically I want to achieve calling some class functions only if they are available (an optional feature) without using Compiler flags in cpp file.

  • 1
    @idclev463035818 Well it kind of is, see https://stackoverflow.com/a/3749780/1968. That said, I see no indication that this should work with class member functions, or more generally with C++ calling conventions (and the attribute should be `weak_import`). – Konrad Rudolph Apr 17 '20 at 08:17
  • @KonradRudolph sorry, my fault. Seems like my reasearch led me to the wrong conclusion – 463035818_is_not_an_ai Apr 17 '20 at 08:19

1 Answers1

0

C++ has a standard mechanism for this. No need for linker tricks.

class Base {
 public:
    virtual void func(int argc, char *argv[]) 
    {
         printf("func() not available\n");
    }
};

class A : public Base {
    public:
#if 0
    void func(int argc, char *argv[]) override;
#endif
};

#if 0
void A::func(int argc, char *argv[]) { 
    printf("In func()\n");
    for(int aa = 0; aa < argc; aa++){
        printf("arg %d = %s \n", aa, argv[aa]);
    }
}
#endif

int main(int argc, char *argv[]) {
    A a1;
    a1.func(argc, argv); 
}
MSalters
  • 173,980
  • 10
  • 155
  • 350