新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > gcc的几个妙用

gcc的几个妙用

作者: 时间:2016-12-01 来源:网络 收藏
下面的代码如下:
  1. foo.c

  2. 1 #include
  3. 2
  4. 3
  5. 4 extern void bar();
  6. 5
  7. 6 void foo()
  8. 7{
  9. 8 printf("This is foo ().");
  10. 9
  11. 10 bar();
  12. 11}

bar.c

本文引用地址:https://www.eepw.com.cn/article/201612/324540.htm

1 #include
2
3 void bar()
4 {
5 printf( " This is bar (). ");
6 }
7

main.c

1 extern void foo();
2
3 int main()
4 {
5 foo();
6
7 return 0;
8 }
~

简要的介绍一些静态库的创建方式。
首先需要注意的时静态编译是指将一些库函数编译到程序中,这样会增加程序的大小。动态库则是在运行过程中添加到程序中,这样可以减小程序的大小。两种方式都有各自的优势。
静态库的创建:
gcc -c foo.c -o foo.o
gcc -c bar.c -o bar.o
创建的基本过程就是采用归档函数实现。
ar csr libfoo.a foo.o
ar csr libbar.a bar.o
从上面的程序我们可以知道foo程序依赖bar程序,而main程序则依赖foo程序,所以这样就形成了一定的关系,一般来说只有将依赖的库函数写在最右边才能保证其他的库函数依赖该库函数。
[gong@Gong-Computer test]$ gcc -o main main.c -L. -lbar -lfoo
./libfoo.a(foo.o): In function `foo:
foo.c:(.text+0x13): undefined reference to `bar
collect2: ld returned 1 exit status
[gong@Gong-Computer test]$ gcc -o main main.c -L. -lfoo -lbar
以上的两个编译过程只是存在一个差异就是库的摆放顺序存在差别,第一种情况下由于foo依赖bar,而bar库不能被foo调用,因此出错。而第二种则满足foo依赖bar,main依赖foo的关系。其中的-L.表示库函数的搜索目录为当前目录。也可以换成其他的目录。
因此在gcc中添加库时,需要注意库名和库的顺序,最好采用一定的依赖关系图分析实现。具体的就要我们在设计程序时自己的考虑各个库函数之间的关系。
至于动态库的创建可以采用gcc实现。其中的-shared就是表明了该库是动态库,-fPCI是指支持PCI,file.o是指需要加载到库中的二进制文件。库名就是libname.so
gcc -shared -fPCI -o libname.so file.o
动态库的使用可以将创建好的动态库放在/usr/lib下,然后在函数中即可实现调用。
gcc的其他一些用法:
查找系统文件路径:gcc -v main.c
获得程序的依赖关系:gcc -M main.c ,其中包括了所有的依赖关系,在写makefile过程中写依赖关系通常不需要系统头文件,这时可以采用gcc -MM main.c去掉系统头文件的依赖关系。
  1. [gong@Gong-Computer test]$gcc-M main.c
  2. main.o:main.c/usr/include/stdio.h/usr/include/features.h
  3. /usr/include/sys/cdefs.h/usr/include/bits/wordsize.h
  4. /usr/include/gnu/stubs.h/usr/include/gnu/stubs-32.h
  5. /usr/lib/gcc/i686-redhat-linux/4.5.1/include/stddef.h
  6. /usr/include/bits/types.h/usr/include/bits/typesizes.h
  7. /usr/include/libio.h/usr/include/_G_config.h/usr/include/wchar.h
  8. /usr/lib/gcc/i686-redhat-linux/4.5.1/include/stdarg.h
  9. /usr/include/bits/stdio_lim.h/usr/include/bits/sys_errlist.h
  10. [gong@Gong-Computer test]$gcc-MM main.c
  11. main.o:main.c
  12. [gong@Gong-Computer test]$

从上面的两个结果就可以知道两个选项的差别,这种差别在编写Makefile中的依赖关系时非常的有用。特别是第二种形式是比较重要的方式。

关于gcc的使用还是要多实践才有效果,才能准确的运用。


上一页 1 2 3 下一页

关键词: gcclinux编译工

评论


技术专区

关闭