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 开发者_如何学C= 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.
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.
If you are just trying to learn and want to see your own code called for abs, min, and gcd you could rename them to something like "my_abs" "my_min" and "my_gcd" in both files and then remove the inline keyword from the declarations.
For example:
// gcd.cpp
// renamed abs to my_abs to avoid name collision with std library function.
int my_abs(int iobj)
{
return (iobj<0?-iobj:iobj);
}
You have some other options like calling abs/min/gcd using the global scope resoultion operation like "::abs(i). But if you are new to programming and just trying to get a feel for writing code I think renaming the functions is the simplest approach to get your feet wet.
Abs is probably working because there is an "abs" function in the std. You should add headers and prototype for your code to work : currently, your file 1 ignores everything that exists in your file 2.
精彩评论