Golang中如何使用CGO添加搜索路径
Golang中如何使用CGO添加搜索路径 当前问题:无法编译包含C代码的项目。
我的项目结构:
----item
----goModule #go module
----include #include .c .h .cxx file
main.go
我运行了命令:
go build -x
得到结果:
TERM='dumb' gcc -I /home/dylan/code/demo/test -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b002=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -DCGO_OS_LINUX=0 -I/home/dylan/code/demo/test/../include -o ./_cgo_main.o -c _cgo_main.c
cd /home/dylan/code/demo
TERM='dumb' gcc -I ./goModule -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b002=/tmp/go-build -gno-record-gcc-switches -o $WORK/b002/_cgo_.o $WORK/b002/_cgo_main.o $WORK/b002/_x001.o $WORK/b002/_x002.o -g -O2 -L/home/dylan/code/demo/goModule/../lib/linux.x64 -lsomelib
/usr/bin/ld: $WORK/b002/_x002.o: in function `function':
/tmp/go-build/cgo-gcc-prolog:52: undefined reference to `function'
我如何在第二条执行语句中添加“-I ./include”。
如果我将所有include/目录下的文件移动到./goModule目录,构建就能成功。
更多关于Golang中如何使用CGO添加搜索路径的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang中如何使用CGO添加搜索路径的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中使用CGO添加搜索路径,可以通过在Go文件中使用#cgo指令来指定C头文件的搜索路径。根据你的项目结构,需要在导入C代码的Go文件中添加相应的编译标志。
在你的main.go或相关Go文件中,添加以下指令:
package main
// #cgo CFLAGS: -I./include
// #include "your_header.h"
import "C"
// 其他Go代码...
如果需要为C++代码指定搜索路径,可以使用CXXFLAGS:
package main
// #cgo CXXFLAGS: -I./include
// #include "your_header.h"
import "C"
// 其他Go代码...
对于链接库的路径,可以使用LDFLAGS:
package main
// #cgo LDFLAGS: -L./lib/linux.x64 -lsomelib
// #include "your_header.h"
import "C"
// 其他Go代码...
如果需要同时指定头文件路径和库路径,可以组合使用:
package main
// #cgo CFLAGS: -I./include
// #cgo LDFLAGS: -L./lib/linux.x64 -lsomelib
// #include "your_header.h"
import "C"
// 其他Go代码...
如果头文件在项目根目录的include文件夹中,而Go模块在goModule目录下,可以使用相对路径:
package main
// #cgo CFLAGS: -I../include
// #include "your_header.h"
import "C"
// 其他Go代码...
对于复杂的项目结构,可以指定多个搜索路径:
package main
// #cgo CFLAGS: -I./include -I../third_party/include
// #cgo LDFLAGS: -L./lib -L../third_party/lib -lsomelib -lotherlib
// #include "your_header.h"
import "C"
// 其他Go代码...
如果需要在不同平台使用不同的路径,可以使用条件编译:
package main
/*
#cgo linux CFLAGS: -I./include/linux
#cgo darwin CFLAGS: -I./include/darwin
#cgo windows CFLAGS: -I./include/windows
#cgo linux LDFLAGS: -L./lib/linux.x64 -lsomelib
#cgo darwin LDFLAGS: -L./lib/darwin -lsomelib
#cgo windows LDFLAGS: -L./lib/windows -lsomelib
#include "your_header.h"
*/
import "C"
// 其他Go代码...
确保在Go文件中正确导入C代码后,重新运行构建命令:
go build -x
这样CGO就会在编译时包含指定的搜索路径,解决未定义引用的问题。

