C++ linkage error for inline member function [duplicate] - c++

This question already has answers here:
Why are C++ inline functions in the header?
(8 answers)
Closed 9 years ago.
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?

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.

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.

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.

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

Related

Undefined symbol error when use inline methods in C++ [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 2 years ago.
When I make method as inline, compilation fails with this error:
Undefined symbol: 'int CPositionRequestor::State(void) const (?State#CPositionRequestor##QBEHXZ)'
Header file:
class CPositionRequestor : public CActive
{
// ...
private:
TInt iState;
public:
inline TInt State() const;
}
CPP file:
inline TInt CPositionRequestor::State() const
{
return iState;
}
An inline function needs it's definition to be available in the file that is calling that function.
So if You define it in one cpp file and try to call it in a second cpp file, then it will not be found.
What You need to do is move this definition into the h file. (just cut & paste it after the class definition).
Or as #einpoklum has noticed, if You don't need it, remove the inline from all the definitions.

MFC projects cause "multiple definition" linker errors?

Is there something special about how an MFC project handles includes?
Here's the scenario. I like to define my class member functions in the h file, instead of splitting up a class between two files.
In Visual Studio I can create an empty Win32 project and do something like this:
main.cpp:
#include "doubleDef.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
doubleDef.h:
#pragma once
class doubleDef
{
public:
int func();
};
int doubleDef::func()
{
return 4;
}
This builds just fine.
If I take doubleDef.h into an MFC dialog project, and add #include "doubleDef.h" to the h file of the main dialog, I get LNK2005, saying that func is already defined, making it seem as if the #pragma once is being ignored.
If I instead include doubleDef.h in the main dialog's cpp file, everything is fine. But in the empty Win32 I can include doubleDef.h "multiple times" by doing this:
Header.h
#pragma once
#include "doubleDef.h"
Header1.h
#pragma once
#include "doubleDef.h"
main.cpp:
#include "Header.h"
#include "Header1.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
That is, it appears #pragma once works as expected (prevents multiple definitions of doubleDef::func()).
If I turn doubleDef into a template class, then the function definition must be in the h file. Likewise, I can make func inline, either by adding the keyword or implicitly by defining it next to the declaration in the class (as in int func() {return 4;}), and then, again the definition must be in the h file.
According to the documentation, the compiler treats inline as more or less optional, so it seems like if I just want to keep everything in the h file, I can just make everything inline.
What gives?
The #pragma once means the file will only be included once per source file. If you have many source files including it, you will still get a copy in each source file.
By declaring a function inline, you tell the compiler it's OK to have multiple copies - as long as those copies are identical.
The usual way of working is to have the declarations in the header file, and the definitions (implementation) in another source file.
P.S. MFC has nothing to do with your problems.
In your simple Win32 project you have one main file that keeps including the same item, basically a no-op. To have multiple of the same include in referenced in the same file does not create a new link.
However with your MFC project you put your header file into mainfrm.h. That file is included in several other files in that project not just the mainfrm.cpp. Essentially creating a new link for each of those other files the main header was included in.
1>MainFrm.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>FileView.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>ClassView.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>OutputWnd.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>PropertiesWnd.obj : error LNK2005: "public: int
__thiscall doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in MfcTest.obj
Take a look at that output. You can see each of the other components that thinks it has that object.
To put it another way your original statement of why does it work for one way and not the other is because the complexity of the second example (MFC) actually includes that header all over the place. If you only want it used by the main form then include it in the cpp for it.
This was already answered before, here is more detailed explanation:
You cannot define a function more than once, unless it is inline
You cannot declare a function more than once in the same file.
You do need to declare functions and classes multiple times if they are referenced in multiple .cpp files.
#pragma once prevents multiple declarations in the same file. It will not prevent multiple declarations in different files. Multiple declarations is exactly what you want and it is why you are including the files in multiple .cpp files in the first place.
class N1 {
public:
//Declaration
//Multiple .cpp files need to know about this class and its members
int foo();
};
//Definition
//should be done once. This should go to .cpp file
int N1::foo() {
return 1;
}
In the above example, compile will work fine in multiple .cpp file. The compile routine does not notice multiple definitions. But the linker notices multiple definitions and complains. You have to move the definition to .cpp file or use inline functions.
class N2
{
public:
int foo();
};
inline int N2::foo()
{ //valid, even if it is repeated in different files
return 1;
}
class N3
{
public:
int foo() //always valid
{
return 1;
}
};

Compilation error while including cpp file in main: Inline versus non-inline functions

I have a conceptual doubt which i'll try to put across using an example:
main.cpp
#include "array_list.cpp"
int main()
{
array_list list1;
return 0;
}
Scenario1:
array_list.cpp->
class array_list
{
private:
int list[10];
public:
array_list () {};
~array_list () {};
void set_element (int,int);
};
void array_list::set_element (int i,int a) {
list[i] = a;
}
Error:
main.obj : error LNK2005: "public: void __thiscall array_list::set_element(int,int)" (?set_element#array_list##QAEXHH#Z) already defined in array_list.obj
1>C:\Users\vrastog\Documents\Visual Studio 2012\Projects\C++ learning\Debug\list using arrays.exe : fatal error LNK1169: one or more multiply defined symbols found
Scenario 2:
array_list.cpp->
class array_list
{
private:
int list[10];
public:
array_list () {};
~array_list () {};
void set_element (int i,int a) {
list[i] = a;
}
};
Error: No error!!
Question: I understand the reason for error. The same method has been defined twice, once in main.obj and second in array_list.obj and hence, it should be an error.
My question is why does the second scenario work? Here also, since we have includes array_list.cpp in the main file, 'set_element' should have been defined twice here as well. What am I missing here?
Please don't include .cpp files.
In the first example, the function is defined out of class, you need to add inline, otherwise it's a multiple definition.
In the second example, the function is defined in the class definition, so it's an implicit inline function (it's like the compiler added the inline for you), that's why it's not causing multiple definitions.
In-class definition makes a method inline, and therefore it does not cause a multiple definition error in the object file.
An inline method should be implemented in every translation unit it is used in, so the inline method compiles into both object files.
C++ Standard Draft (n3797) 3.2.4: An inline function shall be defined in every translation unit in which it is odr-used.
Also 3.2.6 requires that these function should be exactly the same.
g++ implements this using weak symbols: inline functions are special exported functions that do not cause multiple definition error when linking.
Use a tool like nm under Linux and see for yourself. It emits a weak symbol into the object file:
$ nm arraylist.o
00000000 W _ZN10array_list11set_elementEii
(... ctors, dtors ...)
00000000 T main
Also, if you do not use the function, or the compiler inlines all occurrences, it may get optimized out.

LNK 2005 link errors for functions but not for class in Visual Studio 2010

I am now building a C++ DLL library. Today I have met a confusing problem: in this library I can define class but not functions. To be more specific, I give the following codes to illustrate my problem:
namespace fundamental
{
class Tree
{
public:
Tree() {};
~Tree() {};
int x;
};
/*int anyfunction()
{
return 1;
}*/
}
The above definition is in the header file, and this file will be invoked by other files. My problem is that if I commented the function part (int anyfunction()) everything was fine, but if I added this function, I would get the following errors:
page_analysis.obj : error LNK2005: "int __cdecl fundamental::anyfunction(void)" (?anyfunction#fundamental##YAHXZ) already defined in geo_box.obj
1>pa_region_properties.obj : error LNK2005: "int __cdecl fundamental::anyfunction(void)" (?anyfunction#fundamental##YAHXZ) already defined in geo_box.obj
My question is why I will get LNK2005 error only for functions but not for classes. Any ideas?
If you define something in a header file, then that definition will be duplicated in any translation unit (roughly speaking, every source file) that includes that header. Sometimes, multiple definitions are an error.
Classes can be defined in multiple translation units, as long as the definitions are identical; indeed, they must be defined in any translation unit that uses them.
Functions usually can't, but you can allow it by declaring it inline:
inline int anyfunction() {return 1;}
or you could move the definition to a single source file, and only declare it in the header:
// header
namespace fundamental {
int anyfunction();
}
// source file
int fundamental::anyfunction() {return 1;}
Most likely you have included that function via a header into different translation units (aka cpp-file). If you really need that function to be inlined, use "inline":
inline int anyfunction()
{
return 1;
}
HTH Torsten

gtest problem with inline function

hello i have which include inline function, when i try testing this class with google test, i have error like:
error LNK2019: unresolved external symbol "public: double __thiscall Math::returnPi(void)" (?returnPi#Math##QAENXZ) referenced in function "private: virtual void __thiscall Speed_Math_Test::TestBody(void)" (?TestBody#Speed_Math_Test##EAEXXZ)
for example my class(header file)
class Math
{
public:
Math(void);
inline double returnPi();
~Math(void);
};
my class(cpp file)
Math::Math(void)
{}
Math::~Math(void)
{}
double Math::returnPi()
{ return 3.14;}
test:
TEST(EQ, Math)
{
Math *m=new Math();
EXPECT_EQ(3.14,m->returnPi());
}
what i need to do? i read manual but dont see how i can resolved this error.
An inline function should be in your header file, not in your source file so it can actually be inlined by the callers (which don't have access to the source file).
Moreover, you don't need to specify inline in your class declaration if you give the definition of the function.
So your header should become:
class Math
{
public:
Math(void);
double returnPi() { return 3.14; } // no need to specify inline here
~Math(void);
};
And remove the definition for returnPi() from your source file.
Note that you could also have done:
class Math
{
public:
Math(void);
double returnPi();
~Math(void);
};
inline double Math::returnPi() { return 3.14; } // inline is mandatory here to avoid respecting the "One Definition Rule"
The second solution is good if you want to keep the class declaration separate from the function definition.
Also note that inline does not guarantees that the actual function calls will be inlined: the only thing it enforces is that you don't have to respect the "One Definition Rule": the inline function must have the same definition in all translation units.
Are you sure you are compiling the class' CPP file as part of the project? This should be fine.