undefined reference to `memset'

Sean McNeil sean at mcneil.com
Thu Mar 24 20:09:24 PST 2005

On Thu, 2005-03-24 at 19:51 -0800, Vinod Kashyap wrote:
> I did look at your posting Sean, thanks.  But did you see the
> "undefined reference to `memset'" linker error when you built it?
> It's obvious that a reference to memset is being generated by
> the initialization of an array of 100 bytes to 0.  The linker is getting
> the needed memset if you build a stand alone program, or even build a stand
> alone kernel module, but is not being able to find it when building
> the kernel itself.  This implies to me that it is a difference in
> the use of flags, or linking/not linking with particular libraries
> that's causing the problem.

Here is what I believe is happening:

There exists an inline function called memset.  This inline function
_should_ replace any uses of memset within the function when compiled
with optimization (-O or -O2).  In any event that a call is not inlined,
a local copy of memset should be emitted and used.  This is what happens
with -O, but not with -O2.  This is clearly seen by an objdump at each
optimization.  For -O, a local copy of memset is emitted and used.  For
-O2, memset is still called, but the memset code is optimized away.
This is a bug, IMHO, in various ways.

1) -O2 is being too agressive and eliminating memset when it shouldn't.
2) both optimized versions are not replacing the call to memset with the
inline code.

Here is one of several issues with the amd64 compiler used at -O2 vs.
-O.  There are others as well. Note: this comment inserted for the sole
purpose of adding flame-bait :)

You do not need to link to show this.  In fact, since this is a standard
program and memset is available in libc, you will not see the problem in
a link.  You need to look at the nm output and objdump to understand
what is happening.

> I am also confused as to how an explicit call to memset works,
> when compiler generated call doesn't!  Are we talking 2 different
> memset's here?  Maybe a memset and an __memset?

The problem is that the compiler is inserting the memset call.  Either
it is happening too late for inlining to occur or it is done in some
fashion that doesn't lend to inlining by the compiler.  The call inside
the function is handled like all other code and is properly identified
and inlined.  We are not talking about 2 different memset functions, no.
We are talking about 2 different mechanisms for using memset where one
is not properly inlined and the other is.


More information about the freebsd-stable mailing list