GCC和交叉编译中的工具的使用方法
[
编辑]
交叉编译工具简介
交叉工具链名称 | i386的工具名称 | 归属 | 作用 |
arm-linux-as | as | binutils | 编译ARM汇编程序 |
arm-linux-ar | ar | binutils | 把多个.o合并一个.o或是静态库(.a) |
arm-linux-ranlib | ranlib | binutils | 为库文件建立索引,想当于*.as -s |
arm-linux-ld | ld | binutils | 联接器(Linker),把多个.o或是库文件链接一个可以执行文件 |
arm-linux-objdump | objdump | binutils | 查看目标文件的(.o)或是库(.a)的信息 |
arm-linux-objcopy | objcopy | binutils | 转换成可以执行的ELF的文件 |
arm-linux-strip | strip | binutils | 去掉elf可以执行的信息,是可以执行文件变小 |
arm-linux-readelf | readelf | binutils | 读elf的文件头 |
arm-linux-gcc | gcc | gcc | 编译.c和.S的程序和汇编文件 |
arm-linux-g++ | g++ | gcc | 编译个g++程序 |
[
编辑]
c编译语言的例子
分别通过gcc和交叉编译的工具进行编译下面的例子,分别用静态编译、编译成动态库和反汇编的方法。
[
编辑]
hello_first.c
程序源码:
#include <stdio.h>
void hello_first(void)
{
printf("first function /n");
}
[
编辑]
hello_second.c
程序源码:
#include <stdio.h>
void hello_second(void)
{
printf("second function /n");
}
[
编辑]
hello.c
程序源码:
#include <stdio.h>
void hello_first(void);
void hello_second(void);
int main(int argc,char *argv[])
{
hello_first();
hello_second();
}
[
编辑]
编译方法
[
编辑]
编译动态文件
[
编辑]
直接编译
[
编辑]
方法一
#gcc -c hello_first.c
#gcc -c hello_second.c
#gcc -o hello hello.c hello_first.o hello_second.o
[
编辑]
方法二
#gcc -c hello_first.c hello_second.c
#gcc -o hello hello.c hello_first.o hello_second.o
[
编辑]
方法三
#gcc -c -o first.o hello_first.c
#gcc -c -o second.o hello_second.c
#gcc -o hello hello.c first.o second.o
[
编辑]
方法四
#gcc -o hello hello.c hello_first.c hello_second.c
[
编辑]
编译动态库进行编译
#gcc -c -fpic hello_first.c hello_second.c
#gcc -shared hello_first.o hello_second.o -o hello.so
#gcc -o hello hello.c hello.so
/*可以把编译的hello.so拷贝到/lib下或是设定环境变量LD_LIBRARY_PATH指向我们编译的动态库的
文件位置,如,我们把hello.so拷贝到 /tmp下设定LD_LIBRARY_PATH=/tmp,然后重新执行
#./hello*/
[
编辑]
编译成静态库进行编译
#gcc -c hello_first.c hello_second.c
/*建立一个静态的链接库*/
#ar -r libhello.a hello_first.o hello_second.o
/*为静态链接库建立索引*/
#ar -s libhello.a
#ranlib libhello.a
/*由静态库编译成可以执行的文件*/
#gcc -o hello hello.c -lhello -L./
或是
#gcc -o hello hello.c libhello.a
/*编译出来的hello可以脱离libhello.a执行*/
[
编辑]
编译成静态文件
#gcc -static -o hello hello.c hello_first.c hello_second.c
[
编辑]
比较用不同的方便的大小的差异
编译的大小比较
直接编译
编译成动态库
编译成静态库
编译成静态文件
[
编辑]
gcc的使用机巧
在对mp3,video,bmp的文件进行读取的时候,会对文件的头信息或是具体的结构进行读取,
是可以通过进行结构 体进行读取信息,但是在正常编译的时候(gcc),会出现内存的漏洞,
因为在正常定义的时候,编译器会根据具体的系统结构是按整字节处理,这样我们提出的数值
就会出现问题,可以这样解决。
例子:
#include <stdio.h>
int main(int argc,char **argv[])
{
struct test
{
int a;
char b[2];
int c;
};
printf("sizeof(struct test)=%d /n",sizeof(struct test));
}
输出的结果并不是我们所需要的10byte,而是12byte,为什么呢?因为在linux的
4个字节对齐的。在第二个字节里面得就仅仅用了两个字节,可是在我们读取的文件信
息的时候就会出错,可以这样解决:
#include <stdio.h>
int main(int argc,char *argv[])
{
struct test
{
int a;
char b[2];
int c;
} __attribute__((packed));
printf("sizeof(struct test)=%d /n",sizeof(struct test))j;
}