Linking

Hi guys.I have a problem about linkers.I have 2 source files.They are main.c and func.c
1
2
3
4
5
6
7
8
#include<stdio.h>
int z=3;
func(int x)
{
int y;
y=x*x;
return y;
}


1
2
3
4
5
6
7
8
#include<stdio.h>
main()
{
extern int z;
int x=3*z;
int y=func(x);
printf("%d",y);
}


my program is working I compiled files seperately,then I linked them together and i create prog.exe.

but I did not use another header file.İt is possible? when do we use header files?
I did not use header files but I accessed func functon which take part in another files.
Please help.I hope that I wrote succesfully
Last edited on
int y=func(x); that should give you a compile error if you did not forward declare func before.

main() without return ty it should be an error too

Probably you are using some really bad compiler if it allows you that.

#include directive just pastes content of file into current file. To access function defined in another file you need to forward declare them:
Example 1:
1
2
3
4
int main()
{
    func(); //compile error func is not declared anywhere;
}
Example 2:
1
2
3
4
5
void func();
int main()
{
    func(); //compiles fine func is declared and will be bound at link time, will cause an error if there is no such function in any linked file
}
When there is many functions and classes you are using you might not want to manually copy all those function and classes declaration, inline functions, templates and other, so you just place them in header and include them in one line.
I used gcc compiler.
Oh and also func(int x) — you did not write a return type, that is an error too.

There is no way those two code fragments could compile as shown.
Topic archived. No new replies allowed.