Must the inline function be defined in the header file?

Source: Internet
Author: User

Not long ago I was writingCodeWhen a link error occurs, the Code prototype is as follows. Basically, a base class and a derived class are defined, and an inline function defined by the base class is used in a member function of the derived class.

 
// Base. hclass base {protected: void fun () ;}; // base. CPP # include "base. H "inline void base: Fun () {}// derived. h # include "base. H "class derived: public base {public: void g () ;}; // derived. cppvoid derived: G () {fun (); // vc2008: Error lnk2019: unresolved external symbol}

I did not elaborate on this inline function, and the result violates the requirements of the inline function. The so-called inline function is that the compiler expands the function definition (content between {...}) in the function call area to avoid the overhead of the function call. If this function is defined in the header file, all the compilation units that include this header file can find the function definition correctly. However, if the inline function fun () is defined in a compilation unit A, the symbol cannot be parsed where fun () is called in other compilation units, because the target file a is generated in compilation unit. after OBJ, the inline function fun () has been replaced,. OBJ does not contain the "fun" symbol, which cannot be parsed by the linker.

therefore, if an inline function is used in multiple source files, it must be defined in the header file . In C ++, this means If the inline function has the public or protected access attribute, you should do so.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.