If you have your two source files, you can compile them into object files without linking, as so:
Consider a c program which has written in two files named as one.c and two.c:
gcc one.c -o one.o -c
gcc two.c -o two.o -c
where the -c flag tells the compiler to stop after the compilation phase, without linking. Then, you can link your two object files as so:
gcc -o myprog one.o two.o
This is all perfectly normal behavior, you'll usually get your makefile to compile things separately and link them at the end, so you don't have to recompile every single source file every time you change one of them.
Talking about one.o "calling functions in" two.o is perfectly fine, but an .o file is not a source file, it's a compiled object file. If "put my source code in files with extension .o" actually meant "compile my source code into files with extension .o" then the situation would make a whole lot more sense.
//one.c
#include<conio.h>
int i=45;
int j=25;
void main(){
clrscr();
sum();
getch();
}
//two.c
#include<stdio.h>
extern int i; //Declaration of variable i.
extern int j; //Declaration of variable j.
/**
Above two lines will search the initialization statement of variable i and j either in two.c (if initialized variable is static or extern) or one.c (if initialized variable is extern)
*/
extern void sum(){
int s;
s=i+j;
printf("%d",s);
}
[root@cisco project]# gcc one.c -o one.o -c
[root@cisco project]# gcc two.c -o two.o -c
[root@cisco project]# gcc -o myprog one.o two.o
[root@cisco project]# ./myprog
70
Consider a c program which has written in two files named as one.c and two.c:
gcc one.c -o one.o -c
gcc two.c -o two.o -c
where the -c flag tells the compiler to stop after the compilation phase, without linking. Then, you can link your two object files as so:
gcc -o myprog one.o two.o
This is all perfectly normal behavior, you'll usually get your makefile to compile things separately and link them at the end, so you don't have to recompile every single source file every time you change one of them.
Talking about one.o "calling functions in" two.o is perfectly fine, but an .o file is not a source file, it's a compiled object file. If "put my source code in files with extension .o" actually meant "compile my source code into files with extension .o" then the situation would make a whole lot more sense.
//one.c
#include<conio.h>
int i=45;
int j=25;
void main(){
clrscr();
sum();
getch();
}
//two.c
#include<stdio.h>
extern int i; //Declaration of variable i.
extern int j; //Declaration of variable j.
/**
Above two lines will search the initialization statement of variable i and j either in two.c (if initialized variable is static or extern) or one.c (if initialized variable is extern)
*/
extern void sum(){
int s;
s=i+j;
printf("%d",s);
}
[root@cisco project]# gcc one.c -o one.o -c
[root@cisco project]# gcc two.c -o two.o -c
[root@cisco project]# gcc -o myprog one.o two.o
[root@cisco project]# ./myprog
70
No comments:
Post a Comment