Drew LeSueur Drew LeSueur - 14 days ago 5
C Question

How do I access a C constant in Rust?

I am trying to use a C constant in Rust. Here is a portion of the C code:

#define INT_CANCEL 2


In Go, I can do something like this:

return C.INT_CANCEL


How would I do something similar in Rust?

I've tried something like

#[link(name = "name_of_lib")]
extern {
int INT_CANCEL
}


But that doesn't compile.

Answer

I'm no Gopher, but Go doesn't understand C #defines either. Instead, cgo does (at least some subsets of them).

The best and simplest option is copy the value into your program. Note that you have to define a size:

const INT_CANCEL: u8 = 2;

You could also create a macro if you really needed to be able to wait for the type to be decided at runtime, but that's not common.

You could also create a build script that compiles some C code that includes the header and prints out the appropriate Rust code:

#include <stdio.h>
#include "myheader.h"

int main(int argc, char *argv[]) {
  printf("const INT_CANCEL: u8 = %d;\n", INT_CANCEL);

  return 0;
}

That Rust code can then be included back into your project.


You may also try to modify rust-bindgen so that does something similar to cgo and attempts to automatically create these constants.