Search code examples
cmakefileldmemcpy

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!


Solution

  • 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];
        }
    }