- Published on
Why do the Linux use macro over function?
- Authors
- Name
- Bowen Y
Why do the Linux use macro over function?
int __sys_socket(int family, int type, int protocol)
{
struct socket *sock;
int flags;
sock = __sys_socket_create(family, type,
update_socket_protocol(family, type, protocol));
if (IS_ERR(sock))
return PTR_ERR(sock);
flags = type & ~SOCK_TYPE_MASK;
if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
return sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK));
}
SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol)
{
return __sys_socket(family, type, protocol);
}
The use of macros instead of functions in this code is primarily for performance and code size reasons. Let's break down the reasons for using macros in this specific context:
Performance: Macros are expanded inline at compile time, meaning there is no overhead of function call, parameter passing, and return. In performance-critical code paths, avoiding function calls can lead to better performance.
Code Size: By using macros, the code size can be reduced because there is no need to generate function prologue and epilogue for each call. This can be significant in embedded systems or environments where code size is a concern.
Simplicity and Clarity: In this specific case, the macro
SYSCALL_DEFINE3
is likely a macro provided by the Linux kernel for defining system call handlers. It simplifies the process of defining system calls and makes the code more readable by encapsulating the necessary boilerplate code.Integration with Kernel Environment: The use of macros might be dictated by the coding conventions of the Linux kernel. The Linux kernel has its own set of conventions and best practices, and macros are often used in such environments for various purposes, including performance optimization and code readability.
Static Analysis and Optimization: Macros can sometimes enable certain optimizations that might not be possible with function calls. The compiler can perform more aggressive optimizations when dealing with macros, especially if they are simple and don't involve complex logic.
In summary, the use of macros in this code snippet is likely a deliberate choice made for performance, code size, simplicity, and adherence to kernel coding conventions.