Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I found overload functions in linux man page

Tags:

c

overloading

When I man 2 open, I got below:

   int open(const char *pathname, int flags);
   int open(const char *pathname, int flags, mode_t mode);

   int creat(const char *pathname, mode_t mode);

   int openat(int dirfd, const char *pathname, int flags);
   int openat(int dirfd, const char *pathname, int flags, mode_t mode);

It is very like function overload. But it is said that C does not support function overload at all. So what is the magic here?

like image 566
Mr Pang Avatar asked Feb 01 '19 06:02

Mr Pang


2 Answers

These functions aren't really multiple functions, just a single variadic function, accepting variadic arguments, which allows an "overload" in the sense that you can call them with or without their final argument. For example, the actual declaration of openat on my system (omitting attribute tags and the like) is:

extern int openat (int __fd, const char *__file, int __oflag, ...);

That final ... means it can accept additional arguments via stdarg.h's variable arguments APIs (va_start/va_arg/va_end).

like image 181
ShadowRanger Avatar answered Nov 01 '22 17:11

ShadowRanger


To see the actual definition of these functions, run this command:

echo "#include <stdio.h>" | gcc -E - | grep -C5 "open"

This will preprocess the one line of source code and tell you what's happening under the hood.

The result should be something like this:

int open(const char *, int, ...);

This is a typical varargs function like printf, but you as the programmer are supposed to only ever pass a single argument of type mode_t, or none at all.

like image 26
Roland Illig Avatar answered Nov 01 '22 17:11

Roland Illig