在Windows及WSL2运行Mongoose代码时遇标识符/未声明变量错误
尝试运行mongoose的示例代码,按安装说明执行make命令后报错,WSL2中同样失败,但Linux笔记本上运行正常。报错信息如下:
❯ make
gcc main.c mongoose.c -W -Wall -Wextra -g -I. -lws2_32 -DMG_ENABLE_LINES -o example
In file included from main.c:6:
mongoose.h:1:1: error: expected identifier or '(' before '.' token
1 | ../../mongoose.h
| ^
main.c:15:23: warning: 'struct mg_connection' declared inside parameter list will not be visible outside of this definition or declaration
15 | static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
| ^~~~~~~~~~~~~
main.c: In function 'fn':
main.c:16:13: error: 'MG_EV_OPEN' undeclared (first use in this function)
16 | if (ev == MG_EV_OPEN) {
| ^~~~~~~~~~
main.c:16:13: note: each undeclared identifier is reported only once for each function it appears in
main.c:18:20: error: 'MG_EV_HTTP_MSG' undeclared (first use in this function)
18 | } else if (ev == MG_EV_HTTP_MSG) {
| ^~~~~~~~~~~~~~
main.c:20:9: warning: implicit declaration of function 'mg_http_match_uri' [-Wimplicit-function-declaration]
20 | if (mg_http_match_uri(hm, "/websocket")) {
| ^~~~~~~~~~~~~~~~~
main.c:23:7: warning: implicit declaration of function 'mg_ws_upgrade' [-Wimplicit-function-declaration]
23 | mg_ws_upgrade(c, hm, NULL);
| ^~~~~~~~~~~~~
.....
.....
make: *** [Makefile:22: example] Error 1
核心问题是当前示例目录下的mongoose.h并非真实头文件——文件第一行内容是../../mongoose.h,说明这是一个路径占位符或失效的引用文件,导致编译器无法解析头文件的实际内容,进而引发后续一系列未定义标识符、函数隐式声明的错误。
WSL2与本地Linux环境的差异源于文件获取方式:比如克隆仓库时部分文件未完整下载,或跨系统复制示例时仅拷贝了main.c和Makefile,未正确同步mongoose.h和mongoose.c。
- 检查文件完整性:确认示例目录下存在真实的
mongoose.h和mongoose.c,而非仅含路径字符串的占位文件。若缺失,从mongoose仓库根目录复制这两个文件到示例目录。 - 修正头文件引用路径:如果
main.c中的#include "mongoose.h"使用相对路径,确保路径指向正确位置。比如示例目录位于examples/xxx时,应改为#include "../mongoose.h",或直接将mongoose.h放到示例目录下,使用#include "mongoose.h"。 - 重新编译:确认文件无误后,再次执行
make命令。 - WSL2额外检查:建议直接在WSL2内部克隆仓库,避免跨Windows/Linux文件系统复制导致的文件损坏或权限异常。
内容的提问来源于stack exchange,提问作者AwesomeJackify

