Linux tool: Use gcc Programming C

Article Updated: 2020-03-23

First, manually compile a single C source file link

1, create a C source file

Note: Create called here hello.cthe source file.

#include<stdio.h>
int main()
{
  printf("hello,world!\n");
  return 0;
}

2, compile the source file

gcc -c hello.c

Compile

3, to generate an executable file

Note: here resultyou want to output executable file name.

gcc -o result hello.o

executable file

Second, the link manually compile multiple C source files

1, create two C source files

Note: Creating named here hello.cand hello2.cthe 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 *.cto compile multiple C source files.

gcc -c hello.c hello2.c

Generate an object file

3, to generate an executable file

gcc -o result hello.o hello2.o

carried out

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.cand hello2.ctwo 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.othe two object files to be created.
Note 2: The resultexecutable file name to be output.
Note 3: The gccfront 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

executable file

4, add parameters to clean up intermediate files (optional)

Note 1: If you do not want to produce the intermediate *.ofile, 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

Clear intermediate file

四、Enjoy!

Published 75 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_21516633/article/details/105043979