本文介绍了使用-lcjson为c中的json解析器为cjson代码创建一个makefile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对makefile非常陌生.我正在使用命令

I'm very new to the makefiles. I'm compiling the c code file which contains cJson library from terminal using command

gcc -test1.c -o test -lcjson

最后带有-lcjson,并且运行良好.但是如何使用makefile编译相同的代码,因为我最后必须添加-lcjson.如果我在没有-lcjson的情况下使用,则会出错

with -lcjson at last and its running perfectly. But how to compile the same code using makefile as I have to add -lcjson at last.if I'm using without -lcjson I'm getting error

/tmp/cc4ESrx1.o: In function `parse_json':
test1.c:(.text+0x2d): undefined reference to `cJSON_Parse'
test1.c:(.text+0x42): undefined reference to `cJSON_GetObjectItem'
test1.c:(.text+0x59): undefined reference to `cJSON_GetObjectItem'
collect2: error: ld returned 1 exit status

我正在使用RTOS代码

I'm using a RTOS code

预先感谢

推荐答案

首先,避免命名可执行文件test,因为它是标准程序名称(至少在POSIX上如此).

First, avoid naming your executable test since it is a standard program name (at least on POSIX).

然后,阅读 GNU make文档.它包含一个教程部分.

Then, read documentation of GNU make. It contains a tutorial section.

最后,GNU make具有几个内置规则,您可以使用make -p

At last, GNU make has several built-in rules, which you can get with make -p

有关示例,请参见此答案.

我强烈建议使用所有警告和调试信息进行编译(如果使用 GCC gcc -Wall -Wextra -g进行编译) >).因此,在您的Makefile中放入CFLAGS+= -Wall -Wextra -gCC=gcc.

I strongly recommend compiling with all warnings and debug info (that is, with gcc -Wall -Wextra -g if using GCC). So put CFLAGS+= -Wall -Wextra -g and CC=gcc in your Makefile.

要与您的-lcjson链接,请在Makefile中添加LIBES+= -lcjson.请记住,字符在Makefile中非常重要(因此请使用某些编辑器,例如emacs能够对其进行编辑).

To link with your -lcjson add LIBES+= -lcjson in your Makefile. Remember that characters are important in a Makefile (so use some editor, e.g. emacs, able to edit them).

所以尝试:

# your Makefile, replace four spaces with tab
CC= gcc
CFLAGS+= -Wall -Wextra -g
RM= rm -f
MY_SOURCES=$(wildcard *.c)
## above could be an MY_SOURCES= file1.c file2.c otherfile.c
MY_OBJECTS=$(patsubst %.c,%.o,$(MY_SOURCES))
# 
LIBES= -lcjson
#
.PHONY: all clean
##
all: myprog
## 
clean:
     $(RM) myprog *.o *~
myprog: $(MY_OBJECTS)

使用make --trace remake -x调试Makefile

如果您有几个 *.c源文件(即翻译单元)链接到同一个程序中,则应该有一个公共头文件myheader.h(以共享所有公共函数和变量的公共声明),并且应该在每个源文件中#include -ed .然后,您需要依靠它:

If you haver several *.c source files (that is translation units) linked together into the same program, you should have a common header file myheader.h (to share common declarations of all your public functions and variables) which should be #include-ed in every source file. Then you need to depend on it:

 MY_HEADER= myheader.h
 %.o: %.c $(MY_HEADER)

请注意(带有或不带有任何Makefile)程序的顺序gcc 的参数非常重要.参见.

Notice that (with or without any Makefile) the order of program arguments to gcc is very significant. See this.

这篇关于使用-lcjson为c中的json解析器为cjson代码创建一个makefile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 08:11