Sebastien Guimmara
Sebastien Guimmara

Reputation: 175

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() ?

Upvotes: 3

Views: 2116

Answers (2)

user10409664
user10409664

Reputation:

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>

Upvotes: 0

Harry
Harry

Reputation: 11648

You need to use

-std=gnu99

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

Upvotes: 2

Related Questions