Does extern const in C get exported correctly?

I’m not a Odin programmer yet, but maybe soon.

I made an API in C code, and it uses extern const so the struct ends up in a generated .so file.

But it looks like it disappear when using the following…
package plugin_api

import “core:c”

foreign import “C” {
#include “plugin_api.h”
}

and…

odin build plugin.odin -file -build-mode:obj -out:plugin.o

with…
readelf -Ws plugin_gain.o

It is not there.

I know it’s not common to do like this, but my struct must stay intact in the generated elf file, as it’s a pluginformat, and it uses metadata in the .so file so files can be scanned without running code in them.

Welcome to Odin. Not sure if I’m interpretting what I see correctly, but there are some syntax errors (the quotes) in the provided code, plus, .h files I do not believe can be imported.

Message from compiler:

With ‘foreign import’, you cannot import a .h file/directory, you must precompile the library and link against that

So with that, I think it would look more like:

foreign import C {
	// static lib in linux
	"plugin_api.a",
	// shared lib in linux
	"plugin_api.so",
	// static/import library in windows
	"plugin_api.lib",
}

Some links:
Binding to C
Structs

How do you make a struct visible as a global symbol in a object file?

foreign import in Odin is for defining a procedure interface for foreign functions. Any structs that those foreign functions expect would need to be defined in Odin with the correct signatures to work.

How do you make a struct visible as a global symbol in a object file?

In Odin, define the struct as a global constant:

// Constant struct variable, cannot be reused
MyStruct :: struct {
	var1: cstring,
	var2: cstring,
}{
	var1 = "stuff 01",
	var2 = "stuff 02",
}

// or

// struct definition, can be reused for other variables
MyStruct :: struct {
	var1: cstring,
	var2: cstring,
}

// variable defined using struct definition
mystruct :: MyStruct {
	var1 = "stuff 01",
	var2 = "stuff 02",
}

package test

import “core:c”

MyStruct :: struct {
var1: cstring,
var2: cstring,
}

mystruct :: MyStruct {
var1 = “stuff 01”,
var2 = “stuff 02”,
}

Compiles with…
odin build test.odin -file -build-mode:obj

But when I run the following I can’t find it…
readelf -Ws test-builtin.o | grep mystruct

I was not able to export constant structs either. Try this:

MyStruct :: struct {
	var1: cstring,
	var2: cstring,
}

@(export=true, rodata)
mystruct := MyStruct {
	var1 = "stuff 01",
	var2 = "stuff 02",
}

“rodata” makes it read-only, if that’s what you want.

Might also be interested in:
variable-declarations
type-declarations