gcc编译神器之makefile

本机环境是centos6.5 64位。

安装c编译器 :yum install gcc

安装c++编译:yum install gcc-c++

安装make工具:yum install make

上代码:

main.c

#include <stdio.h>
#include "me.h"
void main(){
    int age = getAge();
    printf("my age is %d
",age);
}
~ 

me.c

int getAge(){
        return 18;
}

me.h

int getAge();

makefile

hello:me.c hello.c
        gcc me.c hello.c -o hello

执行 make命令,控制台就会打印出:gcc me.c hello.c -o hello 。
上面的例子贼简单,但能说明问题,如果有成千上百个.c源文件,每次都得一个一个去gcc,那会死人的,如果用make工具,就会变的so easy !

进一步,动态链接库

假设我的me.c的里的功能是一个非常牛逼的东东,我这个hello软件要卖个第三方(队友)使用,我又不想让他知道(修改)我的源代码。这时就可以用动态链接库了。

执行命令:gcc -o libme.so me.c -shared 。当前目录下多了一个libme.so文件。

我们执行gcc -o hello hello.c me.c是可以编译成功的,但这时我们想拿掉me.c源文件,用libme.so去替换,怎么做呢?

执行 gcc -L /usr/local/test/ -l me hello.c -o hello(L后面是libme.so的文件绝对路径,l后面的是名为libme.so当中的me)。

这时发现编译通过了,运行./hello时报“./hello: error while loading shared libraries: libme.so: cannot open shared object file: No such file or directory”。

执行ldd hello (探测程序hello有几个依赖文件)

输出:linux-vdso.so.1 =>  (0x00007fffe3fff000)
     libme.so => not found
     libc.so.6 => /lib64/libc.so.6 (0x0000003c18200000)
     /lib64/ld-linux-x86-64.so.2 (0x0000003c17e00000)

神马?libme.so not found?

linux跟windows一样,有个类似于system32的系统库文件夹,各种公共类库都放在里面。

centos中有两个存放公共库的地方:/lib 、/usr/lib、usr/lib64(64位才有)

执行cp libme.so /lib 和 ldconfig,再运行./hello,妥妥地执行了。

再进一步,安装软件时所用的make 、make install 之谜

修改makefile文件为:

hello:hello.c libme.so
    gcc  -L ./ -l me  hello.c -o hello
    libme.so:me.c
    gcc -shared -o libme.so me.c

install:
   cp ./libme.so /lib
    ldconfig
clean:
   rm -rf hello libme.so /lib/libme.so

删掉之前残留的文件:make clean,爽歪歪
执行:make ,控制台输出:

gcc -shared -o libme.so me.c
gcc  -L ./ -l me  hello.c -o hello

再执行make install,控制台输出:

cp ./libme.so /lib
ldconfig

还可以这样执行 make && make install (当make执行成功时,才执行make intall)。

再执行 ./hello,控制台输出:

my age is 18

微妙之处,请自行体会。

原文地址:https://www.cnblogs.com/airduce/p/7523490.html