2

I started implementing a large program. But I ran into a massive issue. So here is very simplified code of my program. I have a separate .c file for my functions which is normal.c the main program is main.c and I have linked those two with cal.h header file.

main.c

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

void main()
{
    int num1, num2, ans;
    num1=5;
    num2=5;
    ans=add(num1, num2);
    printf("%d" ,ans);
}

normal.c

#include "cal.h"

int add(int num1, int num2)
{
    return num1+num2;
}

cal.h

#ifndef CAL_H_INCLUDED
#define CAL_H_INCLUDED
#include <errno.h>

int add(int num1, int num2);

#endif // CAL_H_INCLUDED

but when I compile this, it gives out the error ..\main.c|10|undefined reference to `add'|

I'm using CodeBlocks v.13.12 in Windows 8.1 Any answer for this question is much appreciated. I tried with CodeLite as well, but the same error occurs. Thank you!

Dinuka Lankaloka
  • 29
  • 1
  • 1
  • 6
  • 4
    When you're linking the files, do you include `normal.o`? – Barmar Jul 11 '14 at 16:45
  • No I didn't. And I'm sorry since I'm new to C I have no idea about working with `.o` files. An explanation would be a great help! – Dinuka Lankaloka Jul 11 '14 at 16:48
  • 2
    I can't speak to how CodeBlocks works, but here's generally how C compilation works. Each .c file is separately *compiled* to a .o file (an "object file"). So your main.c will be compiled to main.o, and normal.c will be compiled to normal.o. Neither of these are executable, and are not complete programs. Then, the two object files are linked together. "Linked" in this case is a technical term, unlike your use -- it's a step performed by the linker. The linker generates your actual executable. Generally IDEs automatically link any .c files in the same project. – EvanED Jul 11 '14 at 16:51
  • Yeah I got it, but this seems it hadn't link those two files. Otherwise the `add` cannot be undefined. Any suggestions to fix this? – Dinuka Lankaloka Jul 11 '14 at 17:02
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Mike Kinghan Jan 08 '18 at 11:38

3 Answers3

2

Complete compilation of the code is required in ubuntu terminal use the following

gcc normal.c main.c -o out -lm
kubuntu
  • 21
  • 2
0

Code blocks have automatic linking but for that you need to have your source and header files under a project.

I had the same issue when I made individual .c & .h files and expected the IDE to link the object files but it failed. I put them under a project and it worked!

Nish
  • 1
  • 1
0

Use complete compilation of your code. if your c codefiles main.c and normal.c are in ./src and header file cal.h is in ./inc follow below method from current dir(.)

g++ ./src/main.c ./src/normal.c -I ./inc -o main

now main is out binary file to execute.