call c function from matlab - c

I got lots of trouble to call c function from matlab.
My c function is simple
test.c
#include "mex.h"
int addOne(int a)
{
return a+1;
}
I typed mex test.c in matlab command window, I got this error message
Undefined symbols for architecture x86_64:
"_mexFunction", referenced from:
-exported_symbol[s_list] command line option
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
mex: link of ' "test.mexmaci64"' failed.
My Matlab is 2013a, osx 10.9, xcode 5.02
Does anybody have an idea about this? Thanks.

Here is a quick example to get you started:
addOne.cpp
#include "mex.h"
double addOne(double a)
{
return a+1;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs!=1 || nlhs>1) mexErrMsgIdAndTxt("mex:error", "Wrong num of args");
if (!mxIsDouble(prhs[0])) mexErrMsgIdAndTxt("mex:error", "Not double");
plhs[0] = mxDuplicateArray(prhs[0]);
double *x = mxGetPr(plhs[0]);
size_t len = mxGetNumberOfElements(plhs[0]);
for (size_t i=0; i<len; ++i) {
x[i] = addOne(x[i]);
}
}
MATLAB:
>> mex -largeArrayDims addOne.cpp
>> x = magic(4)
x =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> addOne(x)
ans =
17 3 4 14
6 12 11 9
10 8 7 13
5 15 16 2

Related

How to install and include a library to my C compiler?

I am using Debian 11
I am trying to reproduce strlcpy.
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4
5 unsigned int ft_strlcpy(char *dest, char *src, unsigned int size)
6 {
7 unsigned int i;
8
9 i = 0;
10 while (src[i] && i < size)
11 {
12 dest[i] = src[i];
13 i++;
14 }
15 dest[i] = '\0';
16 while (src[i])
17 i++;
18 return (i);
19 }
20
21 int main()
22 {
23 unsigned int i;
24 char *dest1 = malloc(sizeof(char) * 50);
25 char *dest2 = malloc(sizeof(char) * 50);
26
27 i = 0;
28 while (i < 26)
29 {
30 printf("%d ", ft_strlcpy(dest1, "hello my name is marcel", i));
31 printf("%s\n", dest1);
32 printf("%ld ", strlcpy(dest2, "hello my name is marcel", i));
33 printf("%s\n", dest2);
34 i++;
35 }
36 free(dest1);
37 free(dest2);
38 return (0);
39 }
However, I get this message when I compile my code:
ft_strlcpy.c: In function ‘main’:
ft_strlcpy.c:32:18: warning: implicit declaration of function ‘strlcpy’; did you mean ‘strncpy’? [-Wimplicit-function-declaration]
32 | printf("%ld ", strlcpy(dest2, "hello my name is marcel", i));
| ^~~~~~~
| strncpy
/usr/bin/ld: /tmp/ccukR8g6.o: in function `main':
ft_strlcpy.c:(.text+0xf0): undefined reference to `strlcpy'
collect2: error: ld returned 1 exit status
make: *** [<builtin>: ft_strlcpy] Error 1
I have no idea how to include libbsd or use pkgconf.
I have tried for a couple of hours, but I couldn't find the solution.
If someone could redirect me to a manual or explain the concepts, that would be great.
Thank you for your help!
The strlcpy function is included in the BSD libc, a superset (extended version) of the POSIX standard library for BSD operating systems. For it to be recognized by the compiler you have to first install the library through your package manager, the name of which will be either libbsd, libbsd-dev or libbsd-devel depending on whether your distribution uses seperate development libraries or not, and than include it as <bsd/string.h>. You can then compile it with (assuming you use GCC) gcc <your-filename>.c -lbsd, specifying the library to be linked. I wouldn't recommended using BSD functions outside of BSD specific software due to portability issues (POSIX incompliences).

I have header file in /usr/include/bpf directory called tracing.h And including it seems to causing problem. I couldn't use it in include w/w-out -I

I have this header and function defined in it called long ptr = PT_REGS_PARM2(ctx); so first running command like following assuming my system config will take care of it finding this header file in /usr/include/bpf/tracing.h.
but couldn't find the header file
root#this:/home/ubuntu/Desktop/ebpf/Linux-exFilter-main/pkg/probe/bpf# clang -O2 -Wall -g -target bpf -I /usr/include/ -c kprobe_send.c -o kprobe_send.o
I also tried with - I and changing <bpf/tracing.h> to "bpf/tracing.h" not worked either.
I started this inclusion of -I after I was compiling this program and it causing error on compile, I could not understand the error but this is following
clang: error: clang frontend command failed with exit code 70 (use -v to see invocation)
#this:/home/ubuntu/Desktop/ebpf/Linux-exFilter-main/pkg/probe/bpf# clang -O2 -Wall -g-target bpf -c kprobe_send.c -o kprobe_send.o
clang: error: unknown argument: '-g-target'
clang: error: no such file or directory: 'bpf'
root#this:/home/ubuntu/Desktop/ebpf/Linux-exFilter-main/pkg/probe/bpf# clang -O2 -Wall -g -target bpf -c kprobe_send.c -o kprobe_send.o
kprobe_send.c:31:2: warning: implicit declaration of function 'srand' is invalid in C99 [-Wimplicit-function-declaration]
srand(time(NULL)); /* Seed the random number generator. */
^
kprobe_send.c:37:11: warning: implicit declaration of function 'rand' is invalid in C99 [-Wimplicit-function-declaration]
int c = randrange(MAX-i);
^
kprobe_send.c:11:22: note: expanded from macro 'randrange'
#define randrange(N) rand() / (RAND_MAX/(N) + 1)
^
kprobe_send.c:51:22: warning: implicit declaration of function 'PT_REGS_PARM2' is invalid in C99 [-Wimplicit-function-declaration]
char *ptr = PT_REGS_PARM2(ctx);
^
kprobe_send.c:51:15: warning: incompatible integer to pointer conversion initializing 'char *' with an expression of type 'int' [-Wint-conversion]
char *ptr = PT_REGS_PARM2(ctx);
^ ~~~~~~~~~~~~~~~~~~
kprobe_send.c:61:22: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'void *' [-Wint-conversion]
bpf_map_update_elem(fd,&key,&data,BPF_ANY);
^~
Error at line 37: Unsupport signed division for DAG: 0x18aff58: i64 = sdiv 0x18af668, 0x18afe20, kprobe_send.c:37:11Please convert to unsigned div/mod.
fatal error: error in backend: Cannot select: 0x18aff58: i64 = sdiv 0x18af668, 0x18afe20, kprobe_send.c:37:11
0x18af668: i64 = sra 0x189bcd8, Constant:i64<32>, kprobe_send.c:37:11
0x189bcd8: i64 = shl 0x189c4f8, Constant:i64<32>, kprobe_send.c:37:11
0x189c4f8: i64,ch,glue = CopyFromReg 0x189c018, Register:i64 $r0, 0x189c018:1, kprobe_send.c:37:11
0x189c150: i64 = Register $r0
0x189c018: ch,glue = callseq_end 0x189bc08, TargetConstant:i64<0>, TargetConstant:i64<0>, 0x189bc08:1, kprobe_send.c:37:11
0x189bfb0: i64 = TargetConstant<0>
0x189bfb0: i64 = TargetConstant<0>
What the above error even means, I thought it was complaining I did not include any headers so I started including tracing.h to cater to PT_REGS_PARM2(ctx)
How can I get rid of this error?
On this line it says unsupported sign division:
Error at line 37: Unsupport signed division for DAG: 0x18aff58: i64 = sdiv 0x18af668, 0x18afe20, kprobe_send.c:37:11Please convert to unsigned div/mod.
Is this line 37 referring to assembly or my source file? In line 37 of source file I am doing
int c = randrange(MAX-i);
Why is the above simple line is not allowed in ebpf program? This is my line 37 and rest of the bpf program
#include <linux/ptrace.h>
#include <linux/version.h>
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <string.h>
#include <sys/sendfile.h>
#include <time.h>
//#include <bpf/tracing.h>
#include <stdlib.h>
#define RAND_MAX 0x7fff
#define PERF_SAMPLE_RAW 1U << 0
#define randrange(N) rand() / (RAND_MAX/(N) + 1)
#define MAX 100000000 /* Values will be in the range (1 .. MAX) */
struct {
__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
__uint(key_size, sizeof(int));
__uint(value_size, sizeof(int));
__uint(max_entries, 100);
} my_map SEC(".maps");
SEC("kprobe/__x64_sys_recvfrom")
int bpf_prog1(struct pt_regs *ctx,int fd, const char *buf, size_t count)
{
static int vektor[100000000];
int candidates[MAX];
int i;
long key;
srand(time(NULL)); /* Seed the random number generator. */
for (i=0; i<MAX; i++)
candidates[i] = i;
for (i = 0; i < MAX-1; i++) {
int c = randrange(MAX-i);
int t = candidates[i];
candidates[i] = candidates[i+c];
candidates[i+c] = t;
}
for (i=0; i<10; i++)
vektor[i] = candidates[i] + 1;
struct S {
int pid;
char cookie[90];
char *ptr;
} data={1,""};
char *ptr = PT_REGS_PARM2(ctx);
//data.pid =count;// bpf_get_current_pid_tgid();
//if(buf==NULL)
//memcpy(data.cookie,buf,20);
data.ptr=ptr;
// data.cookie[0]=buf[0];
//bpf_get_current_comm(&data.cookie, sizeof(data.cookie));
key=vektor[i];
bpf_map_update_elem(fd,&key,&data,BPF_ANY);
//bpf_perf_event_output(ctx, &my_map, 1, &data, sizeof(data));
return 0;
}
char _license[] SEC("license") = "GPL";
int _version SEC("version") = 99;
is there any info source where it says what's allowed or what's not allowed because seems to me its just picking arbitrarily what's allowed and what's not looking into ebpf
My kernel: 5.14.1
My clang: 12
libbpf installed but I'd love to find a command that tells its version and or just where it's installed.
On some link I found it says maybe/or definitely (couldn't tell the difference) be a problem of symlink on Ubuntu exact source .. what this even means does it mean I installed libbpf or something and unbuntu messed up with my symlink that help find libbpf headers? How can I understand what this link says? https://github.com/iovisor/kubectl-trace/issues/76#issuecomment-513587108

Why "undefined symbols" on gcc when main includes header file? [duplicate]

This question already has answers here:
undefined symbol for architecture x86_64 in compiling C program [duplicate]
(1 answer)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 3 years ago.
Why does main.c fail to compile when including sum_divisibles.h?
I am sure I am missing something silly, but can't find it for the life of me.
Compiling on Mac OSX.
sum_divisibles.h
#ifndef SUM_DIVISIBLES
#define SUM_DIVISIBLES
int sum_divisibles(int limit);
#endif /* SUM_DIVISIBLES */
sum_divisibles.c
#include <stdlib.h>
#include "sum_divisibles.h"
int sum_divisibles(int limit)
/* Returns sum of multiples of 3 and 5 less than limit. */
{
int mult_3, mult_5, sum = 0;
for (int ndx=0; (mult_3 = ndx * 3 ) < limit; ndx++) {
if ( (mult_5 = ndx * 5) < limit && mult_5 % 3 != 0 ) {
sum += mult_5 ;
}
}
return sum; }
main.c
#include <stdio.h>
#include "sum_divisibles.h" // does not compile
//#include "sum_divisibles.c" // compiles
int main(void)
{
printf("%d\n", sum_divisibles(1000));
}
Error -- on gcc -Wall main.c
Undefined symbols for architecture x86_64:
"_sum_divisibles", referenced from:
_main in main-e4e97
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

GCC Vector Extensions: AVX2 builtin shuffle crashes when m64 is used

I have the following program in Mingw, gcc 4.9.2:
#include <stdio.h>
#include <stdint.h>
#define VECSIZE 32
typedef char byteVec __attribute__ ((vector_size (VECSIZE)));
#define PERMLEFT_BVEC (byteVec){63,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30}
byteVec permute(byteVec x, byteVec y) {
return __builtin_shuffle(x,y,PERMLEFT_BVEC);
}
void print_vec32b(byteVec a) {
printf("[ ");
int i; for (i = 0; i < 32; ++i) printf("%d ", a[i]);
puts("]");
}
int main() {
byteVec x = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32};
byteVec y = {11,12,13,14,15,16,17,18,19,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,88,89,90,91,92};
byteVec z = permute(x,y);
print_vec32b(x);
return 0;
}
When I compile this program with -m64, it crashes. With -m32 it works fine. Optimization level doesn't matter. I don't understand what's going on. I've also tried TDM with GCC 5.1.0. Same thing. Anybody have any advice? Is it something screwy with GCC in Windows?
Here is the assembly produced by the compiler (note how the shuffle is turned into a permutation automatically, with vperm2i128 and vpalignr, which is the desired behavior:
GCC Explorer
Minimal program: above.
Desired behavior: print permuted byte vector (which it does in 32-bit mode).
Expected output (works in 32-bit mode):
$ gcc nvec.c -m32 -mavx2 -o a.exe && a.exe
[ 92 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ]
Actual result: crash.
Description of crash: immediate crash, windows error reporting bug shows up. No errors or warnings.

Odd duplicate symbol error in C

Ok so i have a project, and i have some helper functions which need to be shared in various other files. call it Helper.c /.h , with the corresponding compilation flag to avoid multiple inclusion (#ifndef SymbolName #define Symbolname blah blahblah #endif). Every file has its header file in the following way:
#include ....
#include ....
#ifndef __FILENAME_H__
#define __FILENAME_H__ //in each file(FILENAME is replaced for the current file's name)
declarations of functions, types, etc.
#endif
I have a compare function, called dummyCompare (templates, so when creating a variable of this ADT, you need to supply your own function pointer for it to work, so for some cases i don't need a specific function, just a generic one, so that is what dummyCompare is.
The error i get when compiling is:
gcc ./Helper.c ./LinkedList.c ./ABB.c ./AVL.c -Wall -lm -D DEBUG -g
duplicate symbol _dummyCompare in:
/var/folders/f2/nghjrbz915vbhjw_1gbb65sm0000gn/T//cc75R4sQ.o
/var/folders/f2/nghjrbz915vbhjw_1gbb65sm0000gn/T//cc8jQwyE.o
ld: 1 duplicate symbol for architecture x86_64
collect2: ld returned 1 exit status
List is used for a non-recursive solution for tree operations in ABB(ABB = BST in spanish)/AVL. Now using Sublime Text 2, i get the following search results for "dummyCompare"
Searching 8 files for "dummycompare"
/dir/ABB.c:
81 if (abb != NULL) {
82 if (ABB_getRoot(*abb) != NULL){
83: list = LL_newList(dummyCompare);
84 LL_insert(list, 1, ABB_getRoot(*abb));
85
/dir/AVL.c:
67 if (avl != NULL) {
68 if (AVL_getRoot(*avl) != NULL){
69: list = LL_newList(dummyCompare);
70 LL_insert(list, 1, AVL_getRoot(*avl));
71
/dir/Helper.c:
2
3 /****************************************************************************
4: * dummyCompare *
5 *****************************************************************************
6 * Retorna si 2 dirrecciones son iguales, necesario para el funcionamiento *
7 * de la lista *
8 ****************************************************************************/
9: int dummyCompare(void * a, void * b)
10 {
11 if (a == b)
/dir/Helper.h:
4
5 int getMax(int a, int b);
6: int dummyCompare(void * a, void * b);
7
8 #endif
5 matches across 4 files
Thing is i can't seem to understand what is wrong, and why am I getting this error. Checked a lot of other question, and only answer i found was ("use #ifndef ... "), which I'm using

Resources