0

I write the following three files: numeros.h, numeros.cpp and main.cpp.

I want to define the inline function outside the body class, in numeros.cpp. Acording to https://isocpp.org/wiki/faq/inline-functions#where-to-put-inline-keyword It's ok to put the inline keyword before the definition. The strange thing is that if I delete inline keyword the program compiles.

//numeros.h
#ifndef NUMEROS_H
#define NUMEROS_H
class Numeros 
{
public:
    Numeros();
    int valor();
private:
    int x;
};
#endif 

-

//numeros.cpp
#include "numeros.h"
Numeros::Numeros() 
{ 
    x = 10; 
}
inline int Numeros::valor()
{
    return x;
}

-

//main.cpp
#include "numeros.h"
#include <iostream>
using namespace std;
int main()
{
    Numeros n1;
    cout<< n1.valor();
    cin.get();
    return 0;
}

EDIT:

Build error on Visual Studio 2015:

1>main.obj : error LNK2019: símbolo externo "public: int __thiscall Numeros::valor(void)" (?valor@Numeros@@QAEHXZ) sin resolver al que se hace referencia en la función _main 1>c:\users\pablo\documents\visual studio 2015\Projects\Project6\Debug\Project6.exe : fatal error LNK1120: 1 externos sin resolver

Build error on Qt Creator 3.5.1:

C:\Users\Pablo\Dropbox\QtProjects\Windows\build-untitled-Desktop_Qt_5_5_1_MinGW_32bit-Debug\debug\main.o:-1: In function `main':

C:\Users\Pablo\Dropbox\QtProjects\Windows\untitled\main.cpp:13: error: undefined reference to `Numeros::valor()'

collect2.exe:-1: error: error: ld returned 1 exit status

Pablo De Luca
  • 795
  • 3
  • 15
  • 29
  • If posting questions related to build errors, then please always include the complete build log (in full and unedited) in the body of the question. – Some programmer dude Dec 12 '15 at 08:19
  • Also note that the `inline` keyword is just a *suggestion* for the compiler, one that it can ignore. Also, it will only affect the current [*translation unit*](https://en.wikipedia.org/wiki/Translation_unit_%28programming%29). – Some programmer dude Dec 12 '15 at 08:21
  • @JoachimPileborg Here I put the build errors. Yes I know that. Thanks :) – Pablo De Luca Dec 12 '15 at 08:25
  • @Gernot1976 I've just tryied it, but the error persist. – Pablo De Luca Dec 12 '15 at 08:26
  • Very heavily related: http://stackoverflow.com/questions/5057021 . Short version: Thinking of `inline` as "I'd like to put this definition in the header file" rather than "I'd like you to try to 'inline' this function" is much more helpful. Playing with compiler and linker optimisation settings is a better way to encourage an implementation to inline functions defined in non-header source files. – CB Bailey Dec 12 '15 at 12:52

1 Answers1

1

The definition of an inline function must be visible wherever that function is called. The problem that the compiler is complaining about is that the definition of Numeros::valor is not visible in main. In order to fix that, the definition has to go in the header, or you have to not mark it inline.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165