2

In my main function I call the functions declared in my header file. I have imported my header file in the main. However, the compiler gives a undefined reference to function. The implementation of the functions of the header file are in another C file. To compile and work my main, I have to import the C file.

My question is: Why do I have to import the C file in addition to the header file.

For example when I include stdlib.h does this file also have the implementations of its functions or just the declarations?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user3213348
  • 255
  • 1
  • 5
  • 14

3 Answers3

2

If your code does not work unless you #include a C file, you are not compiling it right. You should compile the two modules separately, with the main module including only the header for your other module. Then you should link these together.

On UNIX running gcc you can do compilation and linking with a single command:

gcc helper.c main.c

Note: If you are developing on UNIX, you should learn how to use makefiles to manage separate compilation. Here is a tutorial covering the use of makefiles for compiling C++ code.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You don't have to include header files (sometimes), but linking with object files is mandatory. Object file contains the body of functions you try to use and that's why they can't be called without it.

Read further to find out why headers are important and their history

Community
  • 1
  • 1
Basilevs
  • 22,440
  • 15
  • 57
  • 102
0

'#include" just tells the compiler the interface of the file that you are using. (The declaration). #include will make your compiler happy.

In addition you have to have the actual implementation(the definition) which is typically in the *c file. This makes the linker happy.

If you include the stdlib.h - the right C runtime is included for you.

OneGuyInDc
  • 1,557
  • 2
  • 19
  • 50