du16178 2017-11-25 12:20
浏览 84
已采纳

无法使用宏包装cgo标志

I made a Go program to simulate key presses. To do that I had to use cgo and different snippet of C code depending on the OS the Go code was being compiled. The code that I wrote looks like this:

package keyboard

/*
#include <stdint.h>
#ifdef __WIN32
#cgo CFLAGS:-nostdlib
#include <Windows.h>

void SetKey(uint16_t key, uint8_t value) {
    INPUT ip;

    ip.type = INPUT_KEYBOARD;
    ip.ki.wScan = 0;
    ip.ki.time = 0;
    ip.ki.dwExtraInfo = 0;

    ip.ki.wVk = key;
    if (value) {
        ip.ki.dwFlags = 0;
    } else {
        ip.ki.dwFlags = KEYEVENTF_KEYUP;
    }

    SendInput(1, &ip, sizeof(INPUT));
}
#endif

#ifdef __linux__
#cgo LDFLAGS: -lX11 -lXtst
#include <stdlib.h>
#include <stdio.h> //TODO: REMOVE

#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>

void SetKey(uint16_t key, uint8_t value) {
    Display *display;
    display = XOpenDisplay(NULL);

    if(display == NULL) {
        exit(EXIT_FAILURE);
    }

    XTestFakeKeyEvent(display,XKeysymToKeycode(display,key), value, 0);
    XCloseDisplay(display);
}
#endif
*/
import "C"

func SetKey(keyId uint16, value bool) {
    C.SetKey(C.uint16_t(keyId),boolToByte(value));
}

func boolToByte(value bool) C.uint8_t {
    if(value) {
        return 1
    } else {
        return 0
    }
}

The code compiles fine on Ubuntu, but on Windows 10 I get the following error

C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lX11
C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lXtst

even if the line #cgo LDFLAGS: -lX11 -lXtst is wrapped around #ifdef __linux__ and #endif. Where does the problem lie on? Does the GCC compiler define the __linux__ macro? Is the keyword #cgo not supposed to be used like that?

  • 写回答

1条回答 默认 最新

  • dpfl37651 2017-11-25 13:43
    关注

    The #cgo directives are used by the go tools, not the C pre-processor.

    In the cgo documentation, there are examples of using build constraints to conditionally set the flag values. What you want is

    #cgo windows CFLAGS:-nostdlib
    #cgo linux LDFLAGS: -lX11 -lXtst
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于#flink#的问题:关于docker部署flink集成hadoop的yarn,请教个问题flink启动yarn-session.sh连不上hadoop
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题