-1

I try to make program in C and I cant use functions from .h without including .c file too. If I include .c after including .h it works. I get "undefined reference to ..." error on every function defined in .h.

main.c:

#include "mp.h"
//#include "mp.c"
int main()
{
    int n;
    printf("Unesite broj clanova niza: ");
    scanf("%d",&n);
    int *a=(int *)malloc(n*sizeof(int));
    if (a==NULL) exit(0);
    unos(a,n);
    sortiranje(a,n,rastuci);
    stampanje(a,n);
    sortiranje(a,n,opadajuci);
    stampanje(a,n);
    return 0;
}

mp.h:

#ifndef MP_H_INCLUDED
#define MP_H_INCLUDED


#include <stdio.h>
#include <stdlib.h>
enum tip_sort {opadajuci,rastuci};
void unos(int *, int);
void sortiranje(int *, int, enum tip_sort);
void stampanje(int *, int);

#endif // MP_H_INCLUDED

mp.c:

#include "mp.h"


void unos(int *a, int n){
    ...
}
void sortiranje(int *a, int n, enum tip_sort t){
    ...
}
void stampanje(int *a, int n){
    ...
}
  • Please don't [cast the result of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) in C – Iskar Jarak Mar 19 '15 at 20:30

1 Answers1

2

What you're seeing is a linker error. I guess, you're trying to compile main.c all alone.

You compilation statement should look like

gcc main.c mp.c -o output

and yes, do not #include .c (source) files. Source files are meant to be compiled and linked together to form the binary.

Note: Also, please do not cast the return value of malloc().

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I use CodeBlocks and I just hit Build and Run. I dont know what are you referring to by "trying to compile only main.c" – Elektro SRB Mar 19 '15 at 19:13
  • @ElektroSRB I am not familiar with CodeBlocks. What i'm trying to say is add __all__ the source files to the build directory, compile and link them together. Does it make sense? – Sourav Ghosh Mar 19 '15 at 19:19
  • @ElektroSRB maybe as mentioned [here](http://www.codeblocks.org/docs/main_codeblocks_en3.html#x3-30001.1), all your source files should be present in `sources` directory. – Sourav Ghosh Mar 19 '15 at 19:25
  • I do have them in same directory and they are added to project. – Elektro SRB Mar 19 '15 at 19:27