1 year ago

#343809

test-img

Liu Neng

Linker can only find part of .o in .a file

I am trying to use mingw-w64 to create a static lib on windows.
Catalog
Static Lib src:

// test.h
#ifndef __TEST_H
#define __TEST_H

int add(int a, int b);
int div(int a, int b);
int sub(int a, int b);

#endif

// add.c
#include"test.h"

int add(int a, int b)
{
    return a + b;
}

// sub.c
#include"test.h"

int sub(int a, int b)
{
   return a - b;
}

// div.c
#include"test.h"

int div(int a, int b)
{
    return a / b;
}

I use these command to create static lib:

PS D:\ThisPC\Desktop\dlltest> gcc -c *.c
PS D:\ThisPC\Desktop\dlltest> ar rcs libtest.a *.o

Src of app which use this lib:

#include<stdio.h>
#include"test.h"

int main()
{
    int m, n;
    printf("Input two bumbers:\n");
    scanf("%d %d", &m, &n);

    printf("%d / %d = %d\n", m, n, div(m, n));
    printf("%d + %d = %d\n", m, n, add(m, n));
    printf("%d - %d = %d\n", m, n, sub(m, n));

    return 0;
}

Everything is OK.But when I use the lib, I get link error.

PS D:\ThisPC\Desktop\dlltest\app> gcc -I./include -L./lib -ltest -o app main.c  
C:\Users\Admin\AppData\Local\Temp\cc04bSGs.o:main.c:(.text+0x6a): undefined reference to `add'
C:\Users\Admin\AppData\Local\Temp\cc04bSGs.o:main.c:(.text+0x93): undefined reference to `sub'
collect2.exe: error: ld returned 1 exit status

If I delete printf(add()) and printf(sub()) ,it can work.
Linker can only find div label in .a file.

c++

c

mingw

static-libraries

mingw32

0 Answers

Your Answer

Accepted video resources