Search code examples
c++inlinelinkage

Linkage of inline functions


I have 2 files:

1 is main.cpp

#include<iostream>
using namespace std;

int min(int,int);
int abs(int);
int gcd(int,int);

const char *s = "Read Error!!";

int main()
{
  cout << "Enter first Value: ";
  int i;
  cin >> i;
  while(!cin)
  {
    cout << s << endl;
    cin >> i;
  }

  cout << "Enter second Value: ";
  int j;
  cin >> j;
  while(!cin)
  {
    cout << s << endl;
    cin >> j;
  }

  cout << "\nmin: " << min(i,j) << endl;
  i = abs(i);
  j = abs(j);
  cout << "gcd: " << gcd(i,j) << endl;
  return 0;
}

##2 is gcd.cpp
inline int abs(int iobj)
{
  return iobj < 0 ? -iobj : iobj;
}


inline int min(int p1,int p2)
{
  return p1 < p2 ? p1 : p2;
}


int gcd(int v1, int v2)
{
  while(v2)
  {
    int temp = v2;
    v2 = v1 % v2;
    v1 = temp;
  }
  return v1;
}

Now the problem is when 1 compile the 2 files there is no problem for obvious reasons, however i am getting an error at the time of Linking: main.cpp:(.text+0x100): undefined reference to `min(int, int)' When i comment line the statement containing the call of min() it works. Now, why in the world abs() is working, gcd() is working but min() is not??? I am using g++ in Linux.


Solution

  • abs "works" because it is in the standard C library as a regular function. Your homebrew abs never gets exported from its module because it is inline.

    The same happens with min, but that is not available in the standard library, except as a template.

    My advice: import <cstdlib> and <algorithm>, and use std::abs and std::min instead.