how to write a simple makefile for c

后端 未结 3 1402
無奈伤痛
無奈伤痛 2021-01-07 03:43

I need to write a simple make file for my.c, and so after

make

then my program can be run by

./my
相关标签:
3条回答
  • 2021-01-07 03:54

    Well, makefiles are just kind of special scripts. Every is unique, for such simple task this would be sufficient:

    Makefile:

    CC=gcc
    CFLAGS=-lm -lcrypto
    SOURCES=my.c cJ/cJ.c
    
    all: my
    
    my: $(SOURCES)
            $(CC) -o my $(SOURCES) $(CFLAGS)
    

    Later you may want to use some other options such as wildcards %.c to compile in multiple files without having to write them in.

    Alternatively:

    CC=gcc
    CFLAGS=-lm -lcrypto
    
    MY_SOURCES = my.c cJ/cJ.c
    MY_OBJS = $(patsubst %.c,%.o, $(MY_SOURCES))
    
    all: my
    
    %o: %.c
        $(CC) $(CFLAGS) -c $<
    
    my: $(MY_OBJS)
        $(CC) $(CFLAGS) $^ -o $@
    

    Note that lines following each target ("my:", ...) must start with tab (\t), not spaces.

    0 讨论(0)
  • 2021-01-07 04:02

    simple make file for your program is

    build : 
            gcc /your_full_path_to_c_file/cJ.c my.c -lcrypto -o my -lm
    

    just copy this in one file keep name of that file as makefile then run as make build

    0 讨论(0)
  • Just a minor correction: put the -lm to the linking step, and there after all object files.

    all: my
    my: cJ.o my.o
        gcc cJ.o my.o -o my -lcrypt -lm
    cJ.o: cJ/cJ.c
        gcc -c cJ/cJ.c
    my.o: my.c
        gcc -c my.c
    

    And then, you could work more with automatic variables:

    all: my
    my: cJ.o my.o
        gcc $^ -o $@ -lcrypt -lm
    cJ.o: cJ/cJ.c
        gcc -c $^
    my.o: my.c
        gcc -c $^
    

    where $@ is the target of the current rule and $^ are the prerequisites.

    See also http://www.gnu.org/software/make/manual/make.html.

    0 讨论(0)
提交回复
热议问题