[SOLVED] One function for several classes



  • Hi!

    I have got a longer function which is working. It converts number a into number b.
    I need this function in several different classes of QTabWidget. I have defined all tabs as an own class in the header file and they are working fine.
    Of course, it would be possible to include the fairly long code of this function everywhere it is needed.

    Instead of this, I thought it would be better to declare the function once in the header file and refer to it everywhere it is needed.

    In the header file (this is a minimal and adjusted example for demonstration) I have:

    double functionConv(double x) 
    {
       #define number1 (123)
       if(x < 0)
        return log((x+number1)*2);
       else
        return log((x+number1)/2);
    }
    

    and in the .cpp-file of Tab1 to convFun (which is triggered by pushbutton, if it is clicked):

    void Tab1::convFun()
    {
        bool ok;
        double x = lineEditin->text().toDouble(&ok);
        double result=functionConv(x)+123;
    
        QString resultString = "";
        lineEditout->setText(resultString.setNum(result));
    }
    

    Error:

    2 duplicate symbols for architecture x86_64
    linker command failed with exit code 1 (use -v to see invocation)
    

    Or should I write an additional header file just for this function?

    I'd be happy if someone sees the problem.
    Please let me know!



  • If your header really contains the implementation of the function, i.e.

    double functionConv(double x) 
    {
       #define number1 (123)
       if(x < 0)
        return log((x+number1)*2);
       else
        return log((x+number1)/2);
    }
    

    then the error is perfectly normal: the implementation is in every file including that header. You basically have two ways to fix it:

    1. use the inline keyword
    2. split the function definition (i.e. prototype) and implementation in a header file and an implementation file.


  • Excellent answer @JohanSolo !

    I just added "inline" like this:

    inline double functionConv(double x) 
    {
       #define number1 (123)
       if(x < 0)
        return log((x+number1)*2);
       else
        return log((x+number1)/2);
    }
    

    the error messages disappeared and it is possible to call the function in different tabs just with:

       double result=functionConv(x);
    

    The results are correct!

    Thank you very much! Thumbs up!



  • You're welcome!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.