2

I'm trying to link libraries I made to main source code, but it throws this error. I've been searching for last two hours how to fix this but nothing worked for me.

Compiling:

cd "c:\Users\miros\OneDrive\Documents\C codes\labovi"
gcc 01main.c -o 01main
.\01main

d:/programs/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\miros\AppData\Local\Temp\ccGHtHKg.o:01main.c:(.text+0x46): undefined reference to 'faktorijel' d:/programs/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\miros\AppData\Local\Temp\ccGHtHKg.o:01main.c:(.text+0x72): undefined reference to 'suma' collect2.exe: error: ld returned 1 exit status

01ucitavanje.h

#ifndef UCITAVANJE_H
#define UCITAVANJE_H
#include <stdio.h>
#include <stdlib.h>

long long *niz;
int n;

void ucitavanje();
#endif

01ucitavanje.c

#include "01ucitavanje.h"

void ucitavanje(){
    scanf("%d", &n);
    niz = malloc(sizeof(long long) * n);
    for (int i = 0; i < n; i++)
        scanf("%d", niz + i);
}

01izracunavanje.h

#ifndef IZRACUNAVANJE_H
#define IZRACUNAVANJE_H
#include <stdio.h>

long long faktorijel(int n);
long long suma(long long *niz, int n);

#endif

01izracunavanje.c

#include "01izracunavanje.h"

long long faktorijel(int n){
    long long f;
    for (int i = 2; i <= n; i++)
        f *= i;

    return f;
}

long long suma (long long *niz, int n){
    long long s = niz[0];
    for (int i = 1; i < n; i++)
        s += niz[i];
    return s;    
}

main.c

#include "01izracunavanje.h"
#include "01ucitavanje.h"

int main(){
    ucitavanje();
    for (int i = 0; i < n; i++)
        niz[i] = faktorijel((int)niz[i]);
    printf("%d", suma(niz, n));
    free(niz);
    return 0;    
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
qu4lizz
  • 317
  • 2
  • 12

2 Answers2

4

You're compiling only main.c into the executable, so the other functions aren't available.

You need to compile each source file into an object file, then link the object files together.

gcc -c main.c
gcc -c 01izracunavanje.c
gcc -c 01ucitavanje.c
gcc -o 01main main.o 01izracunavanje.o 01ucitavanje.o
dbush
  • 205,898
  • 23
  • 218
  • 273
3

I'm going to give you a mid-line correction because you put your compilation on one very long line.

In this case, you pass all your .c files to gcc. From

{ gcc 01main.c -o 01main }

We'd rather write

{ gcc -o 01main 01main.c 01izracunavanje.c 01ucitavanje.c }

Since you're not actually building a distribution library but rather a bunch of source files we just compile them all together. It generates better code that way anyway once you start optimizing.

Order of .c files doesn't really matter, but the file containing main is first by tradition. Putting -o before the first .c file used to matter and most people still do it.

Joshua
  • 40,822
  • 8
  • 72
  • 132