Including functions in C using heading and additional C files
Trying to call a function from another file in C with the following code:
main.c
#include "display.h"
int main()
{
display_options();
display_price();
return 0;
}
display.h
int display_options(void);
int display_price(void);
display.c
#include <stdio.h>
int display_options()
{
printf("Welcome to the pizza parlor\n");
printf("What size pizza would you like? (in inches)");
return 0;
}
int display_price()
{
printf("Your pizza will cost 0.00\n");
return 0;
}
I created this following an example here http://www.faqs.org/docs/learnc/x307.html but it doesn't seem to be working i get an开发者_StackOverflow error message in codeblocks 10.05 on the function called in main.c saying "undefined reference to 'display_options'"
Looks like you are compiling just the main.c
file.
Make sure you compile as:
gcc -Wall main.c display.c
and run it as:
./a.out
gcc allows you to compile and link a trivial application (has only 1 .c file) in one step.
For applications with more than one .c file, you need to compile all the source (.c) files into object (.o) files. These then need to be linked together.
So you will need to compile each .c file
gcc -c main.c
gcc -c display.c
and then link them using
gcc -o display main.o display.o
This will create the binary display
This can be automated with a Makefile
. you then build the entire thing by just calling make
.
Make sure that #include "display.h"
is also at the top of the display.c
file. Since you are using Code::Blocks, it will automatically compile main.c
and display.c
for you once you do that.
In Code::Blocks, you need to make sure that display.c
is in your project (if you haven't created a project, do so now) and that it's also included in one or more build targets. debug
and release
build targets are created by default, but nothing is added to a target unless you say so. When you create a new file or add an existing file to a project, the IDE should ask you which targets to add the file to. Select all of them and hit OK.
If your file is already in the project but not included in any target, go to Project | Properties | Build targets and make sure that the Build target files panel shows checkmarks beside both main.c
and display.c
.
display.c
#include <stdio.h>
int display_options(void);
int display_price(void);
int display_options()
{
printf("Welcome to the pizza parlor\n");
printf("What size pizza would you like? (in inches)");
return 0;
}
int display_price()
{
printf("Your pizza will cost 0.00\n");
return 0;
}
Now include direct display.c
in the main file instead of display.h
精彩评论