undefined reference to c function when calling from go code - c

Im trying to call a simple c function from within go with cgo
The files are as follows:
goFile.go:
package main
//#include "cFile.h"
import "C"
func main() {
C.printInC()
}
cFile.h:
void printInC();
cFile.c:
#include "cFile.h"
#include <stdio.h>
void printInC(){
printf("Test");
}
running go build goFile.go throws the following exception:
C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: $WORK\b001\_x002.o: in function `_cgo_f9774dcf54b4_Cfunc_printInC':
/tmp/go-build/cgo-gcc-prolog:49: undefined reference to `printInC'
collect2.exe: error: ld returned 1 exit status
I'm not really sure why this isn't working, I've looked at multiple tutorials for cgo that implement calling c functions exactly the same way without a problem.

I've found the problem.
When running go build goFile.go the go tool apparently only builds goFile.go, when i run go build on the entire directory everything works fine..

Related

Undefined reference ld error when using Windows <bluetoothapis.h>

I am new to programming and want to work with the Windows BluetoothApi.h library in C. I've written smaller programs that reference header files I've created, but none of the APIs given by windows.
I am attempting to return information from a local bluetooth speaker to a terminal session on my PC. I've been referencing the BluetoothFindFirstRadio and BLUETOOTH_FIND_RADIO_PARAM documentation, as well as some posts on Stack to see some viable examples. I believe I'm close to being able to compile but I keep getting an error about an undefined reference to the functions I'm calling that I do believe are in the BluetoothAPI.h header file.
From what I've seen, again on Stack, it seems that it's possible that "there is not enough space left at \user\tmp"?
or
Looking at the documentation for ld, it may be possible I need to try to compile using a different command altogther?
PS C:\scripts\C_Lang\Bluetooth> gcc bluetest.c -o test
C:\Users\Ryan\AppData\Local\Temp\cce0FxKH.o:bluetest.c:(.text+0x2b): undefined reference to `BluetoothFindFirstRadio#8'
C:\Users\Ryan\AppData\Local\Temp\cce0FxKH.o:bluetest.c:(.text+0x48): undefined reference to `BluetoothFindRadioClose#4'
collect2.exe: error: ld returned 1 exit status
Code is below:
#include <stdio.h>
#include <string.h>
#include <Windows.h> //not sure if needed
#include <Ws2bth.h> //not sure if needed
#include <bthsdpdef.h>
#include bluetoothapis.h>
//#include <bluetoothleapis.h>
#pragma comment(lib, "Bthprops.lib");
int main(void)
{
BLUETOOTH_FIND_RADIO_PARAMS btfrp; // structure
btfrp.dwSize = sizeof(btfrp); // creating space in memory for parameters?
HANDLE hRadio; // not sure what a handle is, something similar to a pointer?
HBLUETOOTH_RADIO_FIND hFind = BluetoothFindFirstRadio(&btfrp, &hRadio);
// BluetoothGetDeviceInfo(hRadio, &pbtdi);
printf("Bluetooth test!");
BluetoothFindRadioClose(hFind);
return 0;
}
It seems that my issue was not 100% my code, but about how I was attempting to compile my code. After looking further into the documentation I read the line, "Link only to Bthproprs.lib, and avoid linking to Ilprops.lib." So, I don't fully understand why I would need to link, when I have a #pragma comment(lib, "Bthprops.lib"); but that is most likely due to my own ignorance. I did notice the answer on this post which helped clear up my ignorance of HOW to link the Bthproprs.lib library. So, my code didn't change, but my compile did, gcc bluetest.c -o test -lbthprops.
Now, to return something actually useful.

undefined reference to `vec_expand_'

I've come across rxi/vec library for dynamic array implementation for C on GitHub.
I'm trying to run the sample program that is given in the README's usage section.
I've implemented the code like this
#include <stdio.h>
#include "vec.h"
int main()
{
vec_int_t v;
vec_init(&v);
vec_push(&v, 123);
vec_push(&v, 456);
printf("%d\n", v.data[1]); /* Prints the value at index 1 */
printf("%d\n", v.length); /* Prints the length of the vector */
vec_deinit(&v);
return 0;
}
But everytime I'm runnung the program it is throwing this error in the VS Code's terminal:
> Executing task: C/C++: gcc.exe build active file <
Starting build...
Build finished with errors(s):
C:\Users\user\AppData\Local\Temp\cctdgiKc.o: In function `main':
D:/Test.c:9: undefined reference to `vec_expand_'
D:/Test.c:10: undefined reference to `vec_expand_'
collect2.exe: error: ld returned 1 exit status
The terminal process failed to launch (exit code: -1).
On Visual Studio, the error looks something like this...
Visual Studio Error Screenshot
The error appears to be from these two lines:
vec_push(&v, 123);
vec_push(&v, 456);
Also I have tried c-vector library and code from this answer but these are giving same kind of error .
I'm new to C programming so I'm not able to understand what's going on here and it's possible that I might be doing some silly mistake.
Thank you in advance.
You have failed to link the library with your program.
Doing
#include "vec.h"
does nothing to being the actual code in, all it does is to paste in the text of the header (with declarations) at the point of the #include.
The exception is "header only" libraries, but it seems that library is not a header only implementation. The vec_init() function seems to be a macro (or an inline function) since you're not getting errors for it.
You must tell your linker to add the code from the library in question when creating your executable.
How this is done is compiler-specific.

Error accessing aerospike C client through Cgo

I am trying to learn Cgo, so i tried accessing aerospike client from Cgo
package main
// #cgo CFLAGS: -g -Wall
// #include <stdlib.h>
// #include <string.h>
// #include "aerospike-client-c/examples/put/example_utils.h"
import "C"
import (
"unsafe"
)
func main() {
retvals := C.putitnew()
_=retvals
}
But i get below errors. ( Please note the C program runs successfully when i do make and make run ).
undefined reference to `example_get_opts'
./aerospike-client-c/examples/put/example.c:66: undefined reference to
`example_connect_to_aerospike'
./aerospike-client-c/examples/put/example.c:69: undefined reference to
`example_remove_test_record'
./aerospike-client-c/examples/put/example.c:78: undefined reference to
`as_record_init'
./aerospike-client-c/examples/put/example.c:79: undefined reference to
`as_record_set_int64'
/tmp/go-build283334635/b046/_x002.o: In function `as_record_set_str':
....
So i believe the issue is with the configuration in Makefile. I have searched for entire day and tried many solutions but invain. Can you help me how i could import Makefile in Cgo? Or an alternative to help me execute this successfully..
You need to link with the relevant library. I believe the library is called -laerospike. In this case, the cgo directive would look like this:
// #cgo LDFLAGS: -laerospike
See the cgo documentation.
Furthermore, you need to link in the relevant example code. I don't see a put example in the official repository. You will likely have to copy part of its sources directly in the cgo section of your Go file because examples are usually not intended for direct linking.

Using Go code in an existing C project

Ever since Go 1.5 came out, I started taking another look at how I could integrate it into an existing project of mine.
The project's codebase is written entirely in C for low level access to to hardware and other fun stuff. However, some of the higher level things are tedious, and I would like to start writing them in a higher level language (Go)
Is there any way I can call Go code from a C program? I installed Go 1.5, which added -buildmode=c-archive (https://golang.org/s/execmodes) which I am trying to get working.
However, I can't seem to get Go to generate the appropriate header files to allow my project to actually compile. When I generate the archive, I see the function in the exported symbols (using objdump), but without the header files to include gcc complains about the function not existing (as expected)
I'm quite new to Go - however, I love the language and would like to make use of it. Is there any idiomatic way ("idiomatic" gets used a lot in the world of Go I see...) to get this to play nicely with each other?
The reason I asked this question and specifically mentioned Go 1.5 is that according to this document, https://docs.google.com/document/d/1nr-TQHw_er6GOQRsF6T43GGhFDelrAP0NqSS_00RgZQ/edit?pli=1#heading=h.1gw5ytjfcoke
Go 1.5 added support for non-Go programs to call Go code. Specifically, mentioned under the section "Go code linked into, and called from, a non-Go program"
To build an archive callable from C, you will need to mark them as exported CGo symbols.
For example, if I create a file foo.go with the following contents:
package main
import (
"C"
"fmt"
)
//export PrintInt
func PrintInt(x int) {
fmt.Println(x)
}
func main() {}
The important things to note are:
The package needs to be called main
You need to have a main function, although it can be empty.
You need to import the package C
You need special //export comments to mark the functions you want callable from C.
I can compile it as a C callable static library with the following command:
go build -buildmode=c-archive foo.go
The results will be an archive foo.a and a header foo.h. In the header, we get the following (eliding irrelevant parts):
...
typedef long long GoInt64;
...
typedef GoInt64 GoInt;
...
extern void PrintInt(GoInt p0);
...
So that's enough to call the exported function. We can write a simple C program that calls it like so:
#include "foo.h"
int main(int argc, char **argv) {
PrintInt(42);
return 0;
}
We can compile it with a command like:
gcc -pthread foo.c foo.a -o foo
The -pthread option is needed because the Go runtime makes use of threads. When I run the resulting executable it prints 42.
The code above work just fine, but gcc will complain about functions and headers.
The includes should be:
#define _GNU_SOURCE
#include <stdio.h>
#include "mygopkg.h"
If you forget the #define _GNU_SOURCE, the gcc will complain:
warning: implicit declaration of function 'asprintf'; did you mean 'vsprintf'? [-Wimplicit-function-declaration]
If you forget the #include "mygopkg.h", the gcc will complain:
warning: implicit declaration of function 'PrintString' [-Wimplicit-function-declaration]
The last but not less important. The build command line I recommend for production code is:
go build -ldflags "-s -w" -buildmode c-archive -o mygopkg.a
It'll save you 53% size of final mygopkg.a.

libuv undefined reference to uv_loop_new

After compiling, I am trying to run libuv sample program:
#include <stdio.h>
#include <uv.h>
int main() {
uv_loop_t *loop = uv_loop_new();
printf("Now quitting.\n");
uv_run(loop, UV_RUN_DEFAULT);
return 0;
}
But, when try to run, I get the following error:
**/tmp/ccHTpspB.o: In function `main':
main.c:(.text+0x9): undefined reference to `uv_loop_new'
main.c:(.text+0x28): undefined reference to `uv_run'
collect2: error: ld returned 1 exit status**
Where did I go wrong ?
PS: It doesn't work with #include "uv.h"
You need to link the libuv.a with your compiled code and the linker doesn't know where to find the compiled libuv.
To give you a better answer I would need to see you compile command but in the meantime I would strongly recommend this video where Ryan builds a sample libuv project.
The actual code he uses is a little out of date as the API has changed but I think you will find the start where he puts a project together very enlightening.
http://vimeo.com/24713213
In ubuntu I have used following command with success:
gcc sample.c -luv

Resources