简体   繁体   中英

How to use brk()/sbrk() with gcc

I'm writing my own study implementation of malloc() using brk(2) . However, when I try to compile the code with gcc 4.8.4 on Linux Mint 17.2:

gcc -g -O0 -std=c99 -Wall -Werror -pedantic zalloc.c -c -o zalloc.o

I've got the "implicit declaration of function brk" error:

zalloc.c:30:2: error: implicit declaration of function ‘sbrk’ [-Werror=implicit-function-declaration]

I'm already using

#include <unistd.h>

In the file that uses brk() .

Should I link a specific library with -l or -L ? In man brk , there is a cryptic reference to Feature Test Macro requirements for glibc:

Since glibc 2.12:
               _BSD_SOURCE || _SVID_SOURCE ||
                   (_XOPEN_SOURCE >= 500 ||
                       _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) &&
                   !(_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600)
           Before glibc 2.12:
               _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED

Is it necessary to define one of these macros to use brk() ?

You need to use

-std=gnu99

If EOF adds an answer I'll delete this one and upvote his.

On the man page you can read this

"Feature Test Macro Requirements for glibc"

You need to defined _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 500. But clang write

warning: "_BSD_SOURCE and _SVID_SOURCE are deprecated, use _DEFAULT_SOURCE"

#define _XOPEN_SOURCE 500
#define _DEFAULT_SOURCE
#include <unistd.h>

The definition need to be BEFORE #include <unistd.h>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM