Link error with really simple functions C++ on .h file

后端 未结 4 1057
离开以前
离开以前 2021-01-05 19:09

I\'ve made two functions to \'cast\' a 32/64 bit pointer into a double. The code worked when used alone (Just the .h and a .cpp including it) but when using the .h somewhere

4条回答
  •  心在旅途
    2021-01-05 19:25

    Mark your functions inline

    inline double ptr2double(void* pv){
        ptr_u ptr;
        ptr.p = pv;
        return (ptr.d);
    };
    
    inline void* double2ptr(double dv){
        ptr_u ptr;
        ptr.d = dv;
        return(ptr.p);
    };
    

    You see, when you included the same function in two separate source files (translation units), you get multiple definitions. You have generally 2 options:

    • Have delrarations of your funcions in a .h file, and definitions in a separate .cpp file
    • Make your functions inline and keep them in a .h file

    The One-Definition Rule of C++ prohibits multiple definitions of non-inline functions.

    EDIT: The #ifdef guards guard against multiple inclusion into a single source file. But you can indeed include the .h file into different .cpp files. The ODR applies to definitions in the whole program, not just a single file.

    EDIT2 After some comments I feel like I must incorporate this piece of information here lest there should be any misunderstanding. In C++ there are different rules concerning inline functions and non-inline ones, for example the special case of ODR. Now, you may mark any function (be it long or recursive, doesn't matter) as inline, and the special rules will apply to them. It is a completely different matter whether the compiler will decide to actually inline it (that is, substitute the code instead of a call), which it can do even if you don't mark the function as inline, and can decide not to do even if you mark it as inline.

提交回复
热议问题