Article Updated: 2020-03-23
Article Directory
- First, manually compile a single C source file link
- Second, the link manually compile multiple C source files
- Third, the use Makefile to automatically compile link
- 1, create a C source file
- 2, create the Makefile
- 3, do make an executable file
- 4, add parameters to clean up intermediate files (optional)
- 四、Enjoy!
First, manually compile a single C source file link
1, create a C source file
Note: Create called here hello.c
the source file.
#include<stdio.h>
int main()
{
printf("hello,world!\n");
return 0;
}
2, compile the source file
gcc -c hello.c
3, to generate an executable file
Note: here result
you want to output executable file name.
gcc -o result hello.o
Second, the link manually compile multiple C source files
1, create two C source files
Note: Creating named here hello.c
and hello2.c
the two source files.
#include<stdio.h>
int main()
{
printf("hello,world!\n");
testfun(); //调用另一个源文件中的函数
return 0;
}
#include<stdio.h>
void testfun()
{
printf("\nThis is in hello2!\n");
}
2, compiling two source files
Note: Here can also be used gcc -c *.c
to compile multiple C source files.
gcc -c hello.c hello2.c
3, to generate an executable file
gcc -o result hello.o hello2.o
Third, the use Makefile to automatically compile link
1, create a C source file
Note 1: The C source file where the continuation of two of the above-described example.
Note 2: Create named hello.c
and hello2.c
two source files.
#include<stdio.h>
int main()
{
printf("hello,world!\n");
testfun(); //调用另一个源文件中的函数
return 0;
}
#include<stdio.h>
void testfun()
{
printf("\nThis is in hello2!\n");
}
2, create the Makefile
Note 1: Here hello.o
, hello2.o
the two object files to be created.
Note 2: The result
executable file name to be output.
Note 3: The gcc
front of blank lines are Tabgenerated keys.
main: hello.o hello2.o
gcc -o result hello.o hello2.o -lm
3, do make an executable file
4, add parameters to clean up intermediate files (optional)
Note 1: If you do not want to produce the intermediate *.o
file, parameters can be added to clean up in the Makefile.
Note 2: The last line could also be written rm -f *.o
.
main: hello.o hello2.o
gcc -o result hello.o hello2.o -lm
clean:
rm -f hello.o hello2.o