Libc

C main() 的 exit() 和 return

| Development | #C | #Programming | #exit | #return | #main | #libc | #编程

这里讨论一个犀利而无用的细节问题。事情的缘起是有人在 GitHub 上提了一个 pull request 要求把许多程序的 main() 的终结部分从 exit(X) 改为 return X;,我反对了这一变动。

值得注意的是,在实践上,从 mainreturn 和调用 exit(3) 几乎等效的(此处还是有细微差别, 后面将会讨论),原因是 C 运行环境库的启动部分(这部分会在连接过程中嵌入到可执行文件中, FreeBSD 的实现中,这部分位于 lib/libc/csu/libc_start1.c__libc_start1

1
2
3
4
5
6
7
void
__libc_start1(int argc, char *argv[], char *env[], void (*cleanup)(void),
    int (*mainX)(int, char *[], char *[]))
{
/* ... */
	exit(mainX(argc, argv, env));
}
阅读全文…( 本文约 828 字,阅读大致需要 2 分钟 )

Moving toward a standarized qsort_r(3)

History of qsort_r(3)

First introduced in Research Unix V3 and eventually standardized as part of C Standard Library as of ANSI/ISO C89, qsort(3) provided an abstract interface where programmers can perform sort operation over an array of objects, by supplying a pointer to that array, the total number of the member objects, the size of individual member object, as well as a compare function. The compare function is expected to take two parameters, both pointers to a member object, and it shall return a negative number, 0, or a positive number, if the first object is considered smaller, equal, or greater respectively.

阅读全文…( 本文约 2277 字,阅读大致需要 11 分钟 )