Joshua
Joshua

Reputation: 43

undefined reference to `memcpy' error caused by ld

I was developing an embedded project an was struggling to compile it because of this error:
mipsel-linux-gnu-ld: main.o: in function 'fooBar':main.c:(.text+0x3ec): undefined reference to 'memcpy'

This error is caused by every operation similar to this, in which I assign the value of a pointer to a non-pointer type variable.

int a = 0;
int *ap = &a;
int c = *ap; //this causes the error

Here's another example:

state_t *exceptionState = (unsigned int) 0x0FFFF000;
currentProcess->cpu_state = *exceptionState; //this causes the error

I have already included the flag -nostdlib in the makefile...
Thank you in advance!

Upvotes: 3

Views: 9132

Answers (2)

selbie
selbie

Reputation: 104514

I have already included the flag -nostdlib in the makefile...

Take that flag out. It blocks linkage to standard library calls. The compiler might actually generate references to the memcpy function, even if your code doesn't explicitly call it.

If you absolutely need -nostdlib, I suppose you could define your own version of memcpy - if that's the only function the linker is complaining about. It won't be as optimized, but it would work. add the following code to the bottom of one of your source files:

void *memcpy(void *dest, const void *src, size_t n)
{
    for (size_t i = 0; i < n; i++)
    {
        ((char*)dest)[i] = ((char*)src)[i];
    }
}

Upvotes: 1

MadScientist
MadScientist

Reputation: 100836

The fact that you have included -nostdlib is what's causing your problem.

If you copy a structure the compiler may call the standard C runtime function memcpy() to do it. If you link with -nostdlib then you're telling the linker to not include the standard C runtime library.

If you have to use -nostdlib then you'll have to provide your own implementation of memcpy().

Upvotes: 1

Related Questions