一、环境
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 22.04.5 LTS
Release: 22.04
Codename: jammy
suricata: suricata7.0.5
IDE: vscode
二、背景
在suricata中开发了某个功能后,增加unittest时,无法编译通过。
三、unittest增加过程
3.1 增加Add功能
src/util-add.h
#ifndef __UTIL_ADD_H__
#define __UTIL_ADD_H__
int Add(int a, int b);
#ifdef UNITTESTS
void AddRegisterTests(void);
#endif
#endif
src/util-add.c
#include "util-add.h"
int Add(int a, int b)
{
return a+b;
}
#ifdef UNITTESTS
#include "tests/util-add.c"
#endif
3.2 添加源码编译
src/Makefile.am
noinst_HEADERS = \
...
util-add.h \
...
libsuricata_c_a_SOURCES = \
...
util-add.c \
...
3.3 增加unittest
src/tests/util-add.c
#include "util-add.h"
#include "util-unittest.h"
static int AddTest01(void)
{
int a = Add(1, 2);
FAIL_IF(a != 3);
PASS;
}
void AddRegisterTests(void)
{
UtRegisterTests("AddTest01", AddTest01);
}
3.4 注册单元测试
src/runmode-unittests.c
#ifdef UNITTESTS
...
#include "util-add.h"
...
#endif
...
#ifdef UNITTESTS
static void RegisterUnittests(void)
{
...
AddRegisterTests();
...
}
#endif
3.5 编译
$ ./configure --enable-unittest
$ make -j8
四、问题排查
明明有AddRegisterTests
函数的实现,为啥报错说没有实现呢?
经过对比发现vscode
未识别到宏UNITTESTS
的定义
经过查找发现UNITTESTS
定义在src/autoconf.h
,
而src/autoconf.h
是通过文件src/suricata-common.h
引用的
因此在src/util-add.c
中增加 #include "suricata-common.h"
解决。
五、总结
因缺少引用头文件src/suricata-common.h
,导致UNITTESTS宏在util-add.c
中未定义,致使并未编译src/tests/util-add.c
。
以后添加功能,都引用suricata-common.h
头文件,此文件为公共头文件。