+91 9945200008     support@uttaracomputers.com
LOGIN     REGISTER    

C++ Templates - Linker

0
0

Hi MLS Sir , when I was implementing a QUEUE template , I noticed that linker didn’t like having a separate .cpp file for member function definitions.

But when I included the  member func definitions inside the header file queue.h , the issue resolved.

My question is why can’t we have a separate .cpp file for member function definitions for template classes.

Thanks for your valuable c++ course.

 

  • You must to post comments
0
0

Each file you supply on the compilation command line becomes a separate compilation unit for the compiler ( not the linker ). Linker combines all the compiled units to produce the final executable. Included files are part of the same compilation unit since #include is a pre-processor directive of the compiler. The member functions should be included in the same compilation unit to produce object code for the outlined functions. This explains your observation. The class declaration along with inline member functions defined in the class … { } context ( but without outlined member definitions ) can be included by any other compilation unit.

Hope this helps you to understand.

Ex:

c++ aa.cpp bb.cpp cc.cpp

The compiler does 3 separate compilations to produce aa.o, bb.o and cc.o. The linker then combines the three modules to produce the final executable ( which will have the default name “aa” –> the first compilation unit suffix-less file name. The “-o” switch is used to give a different name to the executable. All member functions of a class must be in the same compilation unit for the compiler to produce code.

MLS Shastry

  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.