Reputation: 15
I am just playing around with code blocks and writing a very simple program, but I get the undefined reference error... I copied the exact same code to somewhere else and compiled it in the terminal and works fine, but just doesn't work in code blocks.
my main.c is:
#include <stdio.h>
#include "subfunc.h"
int main()
{
printhello();
return 0;
}
and then my subfunc.c is:
#include <stdio.h>
#include "subfunc.h"
void printhello(void)
{
printf("hello world in function\n");
}
and then my subfunc.h is:
void printhello(void);
Thanks
Actually.. I figured it out. I right clicked the files subfunc.c and subfunc.h and select properties and went to build tab, I find the option for compile file and link file are not ticked. Thanks
Upvotes: 1
Views: 10983
Reputation: 11948
See the above picture and compare with your project. Compare with only the Red colored circle. Ignore the remaining (Remaining are w.r.t my project/assignment)
In my_subfunction.h
write
#ifndef __MY_SUBFUNC_H__
#define __MY_SUBFUNC_H__
#include<stdio.h>
void printhello(void);
#endif
In main.c
#include <stdio.h>
#include "my_subfunc.h"
int main()
{
printhello();
return 0;
}
and my_subfun.c:-
#include <stdio.h>
#include "my_subfunc.h"
void printhello(void)
{
printf("hello world in function\n");
}
I hope this helps.. Because this did work for me.
Upvotes: 2
Reputation: 20838
You didn't state exactly what the undefined error was but I'm betting it has something to do with either your main()
or printhello()
function.
Make sure you're linking both object files main.obj and subfunc.obj in your project after compiling your main.c and subfunc.c. This should automatically happen in codeblocks assuming you included both main.c and subfunc.c for the current project you're building.
Upvotes: 1