uwhpsc-2016 / lectures

Notes, slides, and code from the in-class lectures.
7 stars 21 forks source link

Lecture 7 - example part2-headers #10

Open ckchmod opened 8 years ago

ckchmod commented 8 years ago

I know this lecture was a week ago, but it's been bugging me. In the demo example of showing how .h files are linked to main.c, I think you want #include "sub1.c" to be #include "sub1.h" instead, correct?

cswiercz commented 8 years ago

The purpose of #include is not to include the contents of a source file but to include the necessary function prototypes. This is related to the issue that the following code

// file.c
int main()
{
    int a = square(2);
}

int square(int x)
{
  return x*x;
}

If you tried to compile this code you will end up with at least a warning if not a compile error because by the time the compiler reaches "int a = square(2);" it doesn't know that there exists a function named square(). One solution (a common one) is to provide a function prototype, telling the compiler that "I swear there exists a function called square and it is defined somewhere."

// file.c

int square(int x);  // a function prototype

int main()
{
    int a = square(2);  // compiler now knows that square() is a function defined somewhere
}

int square(int x)
{
  return x*x;
}

Header files are typically used to store function prototypes for the function defined in the corresponding source file. So if sub.c contains the definitions for functions foo() and bar() then sub.h is used to contain their function prototypes.

ckchmod commented 8 years ago

I understand that. But wasn't the point of demo to show how to link sub.h which contains function prototype of sub.c to the main.c file? I just found it initially confusing that we talked about including sub.h,and when we did the demo, we didn't actually use it in main.c.

cswiercz commented 8 years ago

I just reread your initial question and realized that I misunderstood. (Currently bouncing around panicked last-minute questions from other students.) You are correct: the file main.c should read

#include "sub1.h"

at the top, not sub1.c. (The latter works but does something completely different.)

ckchmod commented 8 years ago

Gotcha. Thanks!

cswiercz commented 8 years ago

Reopening because other students may want to read.