CGO 未定义对“TIFFGetField”的引用

CGO undefined reference to `TIFFGetField'

我主要从事 Go 项目 atm,但由于参数传递,我必须将 CGO 用于我的部分项目,目的是使用 C 从 Go 编辑 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的未定义引用”。您很可能错过了共享库的 linking。

我对这个包不太熟悉,但我建议你可以尝试添加如下内容,使你的程序 link 到 C 动态库中:

// #cgo LDFLAGS: -lyour-lib

在上述情况下,我 link 我的 go 程序到名为“libyour-lib.so”的 C 动态库。

例子

假定您的 TIFF 源来自 http://www.simplesystems.org/libtiff/

步骤

  1. 下载源代码
  2. 检查 README.md(或安装)以阅读有关如何编译此 C 库的指南
  3. 按照提供的说明安装 C 库
  4. 如果您在不修改默认设置的情况下操作正确,您应该在 /usr/local/include 中找到 tiff headers,在 /usr/local/lib
  5. 中找到它的动态库
  6. 通过为 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)
}