Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Is inline keyword meaningful if function is defined in header file?</p> </blockquote> <p>It is. Following project will produce linker error on both msvc and g++ BECAUSE of the omission of inline keyword: </p> <hr> <p><strong>main.cpp</strong>:</p> <pre><code>#include "a.h" int main(int argc, char** argv){ A obj; obj.f(); a(); b(); return 0; } </code></pre> <hr> <p><strong>a.h</strong>:</p> <pre><code>#ifndef A_HEADER #define A_HEADER class A{ public: void f(); }; void a(){ } void b(); void A::f(){ } #endif </code></pre> <hr> <p><strong>b.cpp</strong>:</p> <pre><code>#include "a.h" void b(){ A obj; obj.f(); a(); } </code></pre> <hr> <p>*.pro file (for Qt 4 build system):</p> <pre><code>TEMPLATE = app TARGET = DEPENDPATH += . INCLUDEPATH += . HEADERS += a.h SOURCES += b.cpp main.cpp </code></pre> <hr> <p><strong>Compilation output</strong>:</p> <p>cl.exe:</p> <hr> <pre><code>main.obj : error LNK2005: "void __cdecl a(void)" (?a@@YAXXZ) already defined in b.obj main.obj : error LNK2005: "public: void __thiscall A::f(void)" (?f@A@@QAEXXZ) already defined in b.obj debug\1234.exe : fatal error LNK1169: one or more multiply defined symbols found </code></pre> <hr> <p>g++:</p> <hr> <pre><code>debug/main.o: In function `Z1av': D:\c++\1234/a.h:6: multiple definition of `a()' debug/b.o:D:\c++\1234/a.h:6: first defined here debug/main.o:D:\c++\1234/a.h:11: multiple definition of `A::f()' debug/b.o:D:\c++\1234/a.h:11: first defined here collect2: ld returned 1 exit status make[1]: *** [debug/1234.exe] Error 1 make: *** [debug] Error 2 </code></pre> <hr> <p>Now, why do you think this happens? Because compiler <strong>inserts</strong> contents of header file into *.cpp file when compiling. Since function isn't "inline", its name is made known to the linker, and each <em>.obj/</em>.o file will get its own unique copy of <code>A::f()</code> and <code>a()</code>. Linker won't know which you're supposed to use and will complain. If you make functions inline, everything will work fine.</p> <p>However, templates are another story.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload