I'm trying to learn c and I implemented a bubblesort function and i decided It would be better idea if i made a library that will contain various sorting algorithms, so I compiled my code with this:
gcc -shared -fPIC -o bin/bsort.o sort/Bubblesort.c
my bubblesort.c is working (and not related to question at all and there is nothing other than bubblesort function there): // Licensed under public domain with no warranty
void bubblesort(int* array) {
//implemention goes here
}
my sort.h file:
void bubblesort(int* array);
my nsort.c
#include "sort/sort.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main() {
int* sortthis = malloc(1000*sizeof(int));
for(int i = 0; i < 1000; i ) {
*(sortthis i) = random(); //random int is defined somewhere else
}
bubblesort(sortthis);
for(int i = 0; i < 90; i ) {
printf("%d ",*(sortthis i));
}
free(sortthis);
return 0;
}
my script that i use to compile:
gcc -shared -fPIC -o bin/bsort.o sort/Bubblesort.c
gcc nsort.c sort/sort.h -Lbin/bsort.o -lm -o demo.elf
what could be i'm doing wrong, i tried various things but it didn't work, i kept getting following error:
/usr/bin/ld: /tmp/ccxhd5zd.o: in function `main':
nsort.c:(.text 0x23): undefined reference to `bubblesort'
collect2: error: ld returned 1 exit status
gcc --version (just in case if there is a bug in this version):
gcc (Debian 10.2.1-6) 10.2.1 20210110
CodePudding user response:
You don't put -L
before the .o
file. -L
is for adding directories that -l
searches for libraries.
To link with an object file, just add it as an ordinary file argument.
You also don't need to include header files in the compiler arguments. The compiler reads them when it sees #include
.
gcc nsort.c bin/bsort.o -lm -o demo.elf