max() or min() functions in stdlib.h

Asked by Chandan (ಚಂದನ್)

I'm a newbie in Linux arena. I was used to program before in Windows (TC). As I shifted to Linux (GCC), this is my first issue!

I've encountered a linker error while compiling the code:
#include <stdlib.h>
    int main(){

The GCC throws:
    knapsack.c:(.text+0x1de): undefined reference to `max'
    collect2: ld returned 1 exit status

For this, I defined a macro:
#define max(a,b) (a>b?a:b)

Now, it compiles with no issue.

My question is, isn't there library functions like max(), min() (both are there in TC/TC++)..?

Question information

English Edit question
Ubuntu gnome-terminal Edit question
No assignee Edit question
Solved by:
Kevin Hunter
Last query:
Last reply:
Revision history for this message
Best Kevin Hunter (hunteke) said :

As far as I'm aware, there is no max or min function in the C or GNU standard libraries. There is fmax/fmin, but since max and min are so trivial to write ... Here are a couple implementations:

#define ( MAX( a, b ) ( ( a > b) ? a : b ) )
inline int max ( int a, int b ) { return a > b ? a : b; }

Though slightly more general, I'd be wary of the the #define method, as it'll play havoc with post and pre-increment operations. (Although, I'd claim that code like MAX( a++, b ) is bad/poor to begin with.)

As to why they aren't in a library ... there could be a number of reasons; suffice it to say that they aren't.

Revision history for this message
Kevin Hunter (hunteke) said :

Possible reasons why not:

- No agreement on implementation could be reached.
- Naming conflict issues for varying programs that had already been implemented at decision time.
- If they're in a library, it's the overhead of a function call vs 2 loads, a compare, 1 branch, and 2 saves.

(You'll note that max and min are *not* part of the C standard.)

Revision history for this message
Chandan (ಚಂದನ್) (cdn.kit) said :

Thanks Kevin Hunter, that solved my question.