-2

I have the following code:

IFile.h

class IFile
{
public:
    IFile();
    ~IFile(void);

    inline bool IsValidFileType() const;
};

IFile.cpp

IFile::IFile()
{
    //IsValidFileType();
}

IFile::~IFile(void)
{
}

inline bool IFile::IsValidFileType() const
{
          return true;
}

main.cpp

int main(int argc, char* argv[])
{
    IFile* pFile = new IFile();
    pFile->IsValidFileType();

    return 0;
}

When compiling the code I get the following error: error LNK2019: unresolved external symbol "public: bool __thiscall IFile::IsValidFileType(void)const " (?IsValidFileType@IFile@@QBE_NXZ) referenced in function _main

If I change wither "inline" or "const" qualiferes for the function, or call it inside the constructor, the program will complile. Can you please explain this behaviour?

4 Answers4

0

How can the compiler inline a function whose code it cannot see while it is compiling? When compiling main.cpp, the compiler is being asked to do just this.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

An inline function's code gets compiled into each translation unit that references it (that's the idea, after all). Meaning, you need to include the code in the header file.

0

The inline keyword promises to the compiler that it will be able to see the definition in each translation unit (*.cpp file) in which it is used. You break this promise, since main.cpp can't see the definition although it includes IFile.h.

Usually functions with the inline keyword should be defined in a header file, not a source file.

aschepler
  • 70,891
  • 9
  • 107
  • 161
0

Since the function is inline, you have to define it in the header file, not in the cpp file.

NPE
  • 486,780
  • 108
  • 951
  • 1,012