make编译七

当make执行完后,我们期望将最终的可执行文件安装到系统目录下,这样在不同的目录下都可以执行编译的可执行文件,相当于做成了个命令。这个就需要用到make install。

源文件如下:用于判断系统是小端还是大端

#include <arpa/inet.h>
#include <stdio.h>




void big_little_endian()
{
    union{
        short s;
        char c[sizeof(short)];
    }un;
    un.s=0x0102;
    if(sizeof(short) == 2)
    {
        if(un.c[0] == 1 && un.c[1] == 2)
            printf("big_endian
");
        else if(un.c[0] == 2 && un.c[1] ==1)
            printf("little_endian
");
        else
        {
            printf("unknown
");
        }
        
    }
}


void main()
{
    big_little_endian();
}

makefile文件:

subdir:=.
srcfile:=$(foreach dir,$(subdir),$(wildcard $(dir)/*.c))
dir=$(notdir $(srcfile))
objfile=$(patsubst %.c, %.o, $(dir))
targetfile=net_work
cc=gcc
FLAGS=$(addprefix -l,pthread)
prefix = /usr/local
exec_prefix = $(prefix)
bindir = $(exec_prefix)/bin
$(targetfile): $(objfile)
  echo $@
  echo $>
  $(cc) -o $@ $^ $(FLAGS)
$(objfile):$(srcfile)
  echo $>
  $(cc) -c $^

clean:

  rm *.o $(targetfile)
 
install:
  install -d $(bindir)
  install -m 0755 net_work $(bindir)
 
uninstall:
  rm $(bindir)/net_work
 
执行make然后执行make install提示如下错误,这是因为usr/local/bin需要root权限

install -d /usr/local/bin
install -m 0755 net_work /usr/local/bin
install: cannot stat 'net_work': No such file or directory
Makefile:38: recipe for target 'install' failed
make: *** [install] Error 1

加上sudo后执行成功

sudo make install

install -d /usr/local/bin
install -m 0755 net_work /usr/local/bin

这个时候在任意目录下都可以执行net_work。sudo make uninstall则会删除掉对应的目标文件

原文地址:https://www.cnblogs.com/zhanghongfeng/p/13151328.html