Error accessing aerospike C client through Cgo - c

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.

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" error after adding function to a C project

I've added a new function wiringPiVersion() to wiringPi, but after I build and install the shared library, when I attempt to compile a small C program around it, I get:
wpi_ver.c:(.text+0xc): undefined reference to `wiringPiVersion'
However, when I include it in an XS based Perl module, all works well. I don't know enough about C to figure out what's going wrong here, and I've been searching for the better part of two hours trying different things to no avail.
Here's my small C program to test the new function:
#include <stdio.h>
#include <wiringPi.h>
int main (){
char * ver = wiringPiVersion();
printf("wiringPi version: %s\n", ver);
return 0;
}
Compilation that throws the error:
gcc -o ver wpi_ver.c -lwiringPi
The addition to wiringPi's header file:
extern char * wiringPiVersion(void);
The wiringPi's .c file addition:
#define WPI_VERSION "2.36"
char * wiringPiVersion(void){
return WPI_VERSION;
}
In my Perl module's XS file, I have:
char *
wiringPiVersion()
...and my Perl module's Makefile.PL
LIBS => ['-lwiringPi'],
...and after re-installing the Perl module, I can access the function without any issues in a test script.
I'm hoping this is something simple I'm overlooking which someone may be able to point out. My question is, how do I rectify this?
So it turned out that there were two .so files generated when I rebuilt wiringPi... one in the wiringPi's build directory way under my home directory, and the other in /usr/local/lib.
After a tip in comments, I added the library path explicitly:
gcc -o ver wpi_ver.c -L/usr/local/lib -lwiringPi
...and it all fell together and works as expected:
$ ./ver
wiringPi version: 2.36
Note: I have sent Gordon the patch in hopes it gets included in the next wiringPi cut.
Update: I received an email back from Gordon and he stated that currently, only the gpio application has the ability to report the version, so he advised that he's going to add something similar to my patch in a future release.
Although already solved, I added this answer to show what gave me the hint.
Error message "undefined reference" points to a linker error (cf. answer on SO), so its about checking if the correct library is drawn.

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.

Using Go on existing C project

I have a program entirely written in C that uses multiple object (.o) files in it. These files are all packed inside an archive file (.a) which, in turn, is used at compile-time of the program's main (.c) file.
I want to write a new file for this project in Go. My idea is to write this .go file and then create an object (.o) file from it. Afterwards, I want to put this object file inside the already mentioned archive (.a) file.
This basically means that I want to call Go functions from a C program. I've read this question, and while it showed me that what I want is possible via GCCGO, it's not 100% clear as to how to do it.
Even with the most basic of tests, I get errors during the linking phase. More specifically, here's one of such basic example:
printString.go
package main
import
(
"fmt"
)
func PrintString(buff string) int {
fmt.Printf(buff)
return 1
}
c_caller.c
#define _GNU_SOURCE
#include <stdio.h>
extern int PrintString(char*) __asm__ ("print.main.PrintString");
int main() {
char *string_to_pass= NULL;
asprintf(&string_to_pass, "This is a test.");
int result= PrintString(string_to_pass);
if(result) {printf("Everything went as expected!\n");}
else {printf("Uh oh, something went wrong!\n");}
return result;
}
Compiling
In order to compile the Go file, I used this command:
gccgo -c printString.go -o printString.o -fgo-prefix=print -Wall -Werror -march=native
In order to compile the entire thing, I used this command:
gccgo -o main c_caller.c printString.o -Wall -Werror -march=native
The return message I'm getting is:
/usr/lib64/libgo.so.4.0.0: undefined reference to `main.main'
/usr/lib64/libgo.so.4.0.0: undefined reference to `__go_init_main'
collect2: error: ld returned 1 exit status
Which means that GCCGO's expecting a main function in the Go file instead of the C one.
Using the --static-libgo, -static and -Wl,-R,/path/to/libgo.so's_folder options on the second command yield a different result:
/usr/bin/ld: cannot find -lgo
collect2: error: ld returned 1 exit status
Which makes no sense, since I have the LD_LIBRARY_PATH environment variable properly pointing to libgo.so's folder.
I realize that I'm probably doing something wrong here, but I just can't see what that is. There's next to no examples of GCCGO and its interaction with C out there, and the only reference I could find was this page, which I personally feel like it's not enough.
I ask kindly for some advice on this matter and thank you for your time. :)
This may not be what you want, but in Go 1.5, that's coming this August, you'll be able to build C-compatible libraries with the go tool. So with this in your _main.c
#include <stdio.h>
int main()
{
char *string_to_pass = NULL;
if (asprintf(&string_to_pass, "This is a test.") < 0) {
printf("asprintf fail");
return -1;
}
PrintString(string_to_pass);
return 0;
}
and this in your main.go
package main
import "C"
import "fmt"
//export PrintString
func PrintString(cs *C.char) {
s := C.GoString(cs)
fmt.Println(s)
}
func main() {}
You can do, for static library:
go build -buildmode c-archive -o mygopkg.a
gcc -o main _main.c mygopkg.a -lpthread
For shared library:
go build -buildmode c-shared -o mygopkg.so
LD_RUN_PATH=$(pwd) gcc -o main _main.c mygopkg.so -lpthread
(LD_RUN_PATH is here to make the linker look for the shared library in the same directory you're building.)
See the Go execution modes design document for more info.
There currently isn't a supported way to do what you want. Go always needs the support of its runtime, and the entry point for that is always main. AFAIK, gccgo also makes these same assumptions, and doesn't provide a way to easily link into from other programs.
If you want to do this in a supported manner, you will have to wait until go1.5+ where work is being done to compile shared libraries from Go code.
If you really want to hack on this now, you can look into how the Android port works using the default gc toolchain with -linkmode external, which renames main in the object file and calls it externally.

Undefined references when compiling gSOAP client

I'm trying to create a client for a web service in C. I was generated C files with the wsdl2h and soapcpp2. In netbeans I'm added the generated files and the gSOAP include dir to the project's include directories.
my main file looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <soapH.h>
#include <webserviceSoap12.nsmap>
int main(int argc, char** argv) {
struct soap *soap1 = soap_new();
struct _ns1__getAllCustomer *quote;
struct _ns1__getAllCustomerResponse *quote2;
if (soap_call___ns2__getAllCustomer(soap1, NULL, NULL, quote, quote2) == SOAP_OK)
printf("asd\n");
else // an error occurred
soap_print_fault(soap1, stderr); // display the SOAP fault on the stderr stream
return (EXIT_SUCCESS);
}
I copied the most of this from the gSOAP website's getting started section.
When I try to compile i get the following error:
build/Debug/MinGW-Windows/main.o: In function `main':
\NetBeansProjects\WebServiceClient/main.c:19: undefined reference to `soap_new_LIBRARY_VERSION_REQUIRED_20808'
\NetBeansProjects\WebServiceClient/main.c:22: undefined reference to `soap_call___ns2__getAllCustomer'
\NetBeansProjects\WebServiceClient/main.c:25: undefined reference to `soap_print_fault'
If I add the "soapC.c" "soapClient.c" "soapClientLib.c" files to the project I get a bunch of more undefinied reference.
What am I doing wrong? I'm using Netbeans ide with MinGW compiler on Win7. What other libraries I need or what other files should I include?
I managed to solve the problem by adding the files "soapC.c" "soapClient.c" "stdsoap.c" to the project files and in the Project propertie - Include Directories adding the files generated by soapcpp2 and the gSOAP toolkit's gsoap directory
You will need to link in the proper libraries. You will need to add the appropriate libraries using the -l switch and you will optionally need to pass the path to where these libraries reside via -L. Also, note that the libraries ending with a ++ are typically the ones you should use if you're using C++. So, your command line shoulde include at least:
For C:
gcc ... -lgsoap -L/path/to/gsoap/binaries
For C++:
g++ ... -lgsoap++ -L/path/to/gsoap/binaries
Also, depending on whether you're using additional features such as SSL, cookies etc. you will need to link these libraries in too:
g++ ... -lgsoap++ -lgsoapssl++ -L/path/...
If you're using a different toolchain, lookup the documentation for the exact switches.
I had this problem in Debian BullsEye (11), -lgsoap++ is necessary and it was solved when I added /gsoap_library_path/libgsoap++.a to g++ compiler command line.

Resources