c - CGO对“TIFFGetField”的 undefined reference

标签 c windows go cgo lib

我主要在Go项目atm上工作,但是由于参数传递,我必须使用CGO作为我项目的一部分来编辑Go with C的TIF文件。我不熟悉C,但这似乎是解决我们问题的唯一方法。
问题是,当我从理论上设置Go部件并想使用我的C代码时,它通过TIFFGetField,_TIFFmalloc,TIFFReadRGBAImage函数调用删除了undefined reference to xxxx'`。
可能我什至没有以正确的方式导入libtiff库。
有趣的是,C代码本身的第一个代码是TIFF* tif = TIFFOpen("foo.tif", "w");没有对TIFFOpen的引用错误,只有其他错误(TIFFGetField,_TIFFmalloc,TIFFReadRGBAImage,_TIFFfree,TIFFClose)
我的代码是

package main

// #cgo CFLAGS: -Ilibs/libtiff/libtiff
// #include "tiffeditor.h"
import "C"

func main() {
    C.tiffEdit()
}
#include "tiffeditor.h"
#include "tiffio.h"

void tiffEdit(){
    TIFF* tif = TIFFOpen("foo.tif", "w");
    if (tif) {
        uint32 w, h;
        size_t npixels;
        uint32* raster;

        TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
        TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
        npixels = w * h;
        raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
        if (raster != NULL) {
            if (TIFFReadRGBAImage(tif, w, h, raster, 0)) {
            //
            }
            _TIFFfree(raster);
        }
        TIFFClose(tif);
    }
}
我的首要目标只是使用我的go代码建立libtiff并使其能够识别libtiff函数,因此我可以专注于解决问题本身。

最佳答案

如果您在cgo中看到消息“未定义对xxx的引用”。您很可能会丢失与共享库的链接。
我对这个软件包不太熟悉,但是我建议您可以尝试添加以下内容,以使程序链接到C动态库:

// #cgo LDFLAGS: -lyour-lib
在上述情况下,我将go程序链接到一个名为“libyour-lib.so”的C动态库。

假设您的TIFF来源来自http://www.simplesystems.org/libtiff/
脚步
  • 下载源代码
  • 检查README.md(或INSTALL)以阅读有关如何编译此C库的指南
  • 按照提供的说明进行操作并安装C库
  • 如果在正确的情况下未修改默认设置,则应该在/ usr / local / include中找到tiff头,在/ usr / local / lib中找到其动态库
  • 通过为cgo编译器提供适当的提示,将这些内容集成到go程序中。

  • 代号
    我已经成功构建了该程序,并按预期执行。对于您来说,这可能是一个很好的起点。
    package main
    
    // #cgo LDFLAGS: -ltiff
    // #include "tiffio.h"
    // #include <stdlib.h>
    import "C"
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        path, perm := "foo.tif", "w"
    
        // Convert Go string to C char array. It will do malloc in C,
        // You must free these string if it no longer in use.
        cpath := C.CString(path)
        cperm := C.CString(perm)
    
        // Defer free the memory allocated by C.
        defer func() {
            C.free(unsafe.Pointer(cpath))
            C.free(unsafe.Pointer(cperm))
        }()
    
        tif := C.TIFFOpen(cpath, cperm)
        if tif == nil {
            panic(fmt.Errorf("cannot open %s", path))
        }
    
        C.TIFFClose(tif)
    }
    

    关于c - CGO对“TIFFGetField”的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63921892/

    相关文章:

    c++ - 令人困惑的 fork 系统调用

    c - 是否可以映射一个非常大的文件并使用 qsort?

    c - 如何使用 C 中使用数组作为参数的函数进行递归?

    c++ - 在内联汇编中访问 C 结构成员

    将空指针(数据)转换为函数指针

    无论我做什么,JavaScript 文件都不会更新

    go - 当从 Golang 中的另一个包调用时,全局变量变为 nil

    java - 尝试创建批处理文件来运行 Java 程序时无法找到或加载主类

    json - 使用 gorm 创建记录时如何验证所属关系

    go - golang报错函数如何获取编译信息