Problems with ld, libc, and "struct stat"

Jan Behrens jbe-mlist at
Wed Oct 16 11:15:55 UTC 2019

On Wed, 16 Oct 2019 09:18:52 +0200
David Demelier <markand at> wrote:

> Le 15/10/2019 à 20:44, Jan Behrens a écrit :
> > I stumbled across a weird problem related stat() that (according to my
> > research) seems to be related to an update of the "struct stat"
> > C-structure in recent Kernel versions.
> > 
> > [...]
> > 
> >    stat("testlib.c", &sb);
> Please test the result of stat otherwise sb is left untouched (so all 
> member undefined).

You are right, of course (this was just a quick and dirty demonstration).

> > But when I make a shared library like this, I get a different result:
> > 
> > % ld -shared -o testlib.o
> Hmm, we usually never call the linker itself when creating shared libraries.
> Try instead: cc -shared -o testlib.o
> -- 
> David

Thank you very much; I tried that, and it works properly:

% cc -Wall -c -fPIC -o testlib.o testlib.c
% cc -shared -o testlib.o
% cc -Wall -o testprog `pwd`/ testprog.c
% ./testprog 
Size of testlib.c is 168 bytes.

I will from now on use cc instead of ld to create shared libraries.

I still wonder though if there is any documentation on this behavior
(and where to find it), whether it's FreeBSD related or LLVM related.
It feels a bit scary that using "ld" to make a shared library can
result in weird runtime behavior without even raising a warning.

Do you know any link where I find a more detailed explanation about why
I need to use "cc" instead of "ld" to create shared libraries? I assume
that "cc" adds the necessary options to "ld" that are otherwise
missing. But I don't see where this is documented.

When I search the man page for "cc" (clang - the Clang C, C++, and
Objective-C compiler), I even do not find any "-shared" option at all.

Only in the "ld" manpage (ld.lld – ELF linker from the LLVM project),
there is an entry about the "-shared" option:

             Build a shared object.

Following the man pages, I would naïvely use "ld", which leads to the
bad and unexpected results as described in my original post.

Thanks again

P.S.: My setup is:

% freebsd-version

% uname -i -K -m -p -r -s -U -v
FreeBSD 12.0-RELEASE-p10 FreeBSD 12.0-RELEASE-p10 GENERIC  amd64 amd64 GENERIC 1200086 1200086

% cc --version
FreeBSD clang version 6.0.1 (tags/RELEASE_601/final 335540) (based on LLVM 6.0.1)
Target: x86_64-unknown-freebsd12.0
Thread model: posix
InstalledDir: /usr/bin

% ld --version
LLD 6.0.1 (FreeBSD 335540-1200005) (compatible with GNU linkers)

More information about the freebsd-questions mailing list