gcc shared library with header in the same library - c

I'm trying to compile a shared library (.so) with the following code:
libreceive.h:
#include <stddef.h>
int receive(int sockfd, void *buf, size_t len, int flags);
libreceive.c
#include <stddef.h>
#include <libreceive/libreceive.h>
int receive(int sockfd, void *buf, size_t len, int flags){
return recv(sockfd, buf, len, flags);
}
the problem here is that I'm trying to include the .h in the library that I'm building and using it in the same time from the same library in the .c .
I know that what I'm trying to do is possible, but I can't manage to do it.
How can I do that please.
the code I'm trying is:
gcc -o libreceive.o -c -include libreceive.h libreceive.c
I get the following error:
fatal error: libreceive/libreceive.h: No such file or directory
compilation terminated.
the problem here is that I'm trying to include the .h in the library that I'm building and using it in the same time from the same library in the .c .
I know that what I'm trying to do is possible, but I can't manage to do it.
How can I do that please.

Since libreceive.h and libreceive.c appear to be in the same directory (judging from your compiler call), the normal way is
#include "libreceive.h"
In order to use
#include <libreceive/libreceive.h>
libreceive.h would have to lie in a directory called libreceive, and that directory would have to be part of the include path. It is possible to achieve this, but I believe it is neither necessary nor useful here.

You are missing out a few steps here.
Consider the following setup.
File: add.c
#include "header.h"
int add(int a, int b)
{
printf("SIZE: %d\n", SIZE);
return a+b;
}
File: sub.c
#include "header.h"
int sub(int a, int b)
{
printf("SIZE: %d\n", SIZE);
return a-b;
}
File: header.h, located in directory called include.
#include <stdio.h>
#define SIZE 100
int add(int a, int b);
int sub(int a, int b);
So to step by step build a .so file.
/* Build `.o` files first */
$ gcc -fPIC -c sub.c -I path/to/include/
$ gcc -fPIC -c add.c -I path/to/include/
/* Build shared library called libsample.so */
$ gcc -shared -o libsample.so add.o sub.o
The above command will build a .so by name libsample.so.
Where all definition from .c(like functions) and .h(like #defines) will get included in your library.
How to use this in your code:
Consider the file
File: main.c
#include <stdio.h>
int main()
{
int a = 3, b = 4;
printf("Return : %d\n", add(a, b));
return 0;
}
To make use of your library libsample.so.
$ export LD_LIBRARY_PATH=/path/to/direc/containing/.so/file
$ gcc -o exe main.c -lsample -L/path/to/direc/containing/.so/file
The above command should create a binary called exe.
$./exe
SIZE : 100 /* SIZE Defined in .h file */
Return : 7 /* Defined in add.c */
You can refer this guide : http://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html

Finaly I decided to use #include "libreceive.h" as suggested by the guys. the probleme I had is that the compiler was looking for my so in /usr/lib wich is the default when id do sudo gcc and my usr had the $LD_LIBRARY_PATH at /usr/local/lib and therefore gcc coudn't find my library at compile time
another problem was that the program that call thos .so was looking fro the .h in some folder that doesn't exist and I had to add it.
thanks guys for you answers

Related

how to use generated code from matlab

I want to use the C-coder in Matlab. This translates an m-code to C-code.
I use a simple function that adds 5 numbers.
When the code is generated there are a lot of C- and H-files.
of course you could just pick the code you need and import it in your code, but that's not the point of this exercise, as this will no longer be possible when the matlab-code will get more difficult.
Matlab delivers a main.c file and a .mk file.
/* Include Files */
#include "rt_nonfinite.h"
#include "som.h"
#include "main.h"
#include "som_terminate.h"
#include "som_initialize.h"
//Declare all the functions
int main(int argc, const char * const argv[]){
(void)argc;
(void)argv;
float x1=10;
float x2=20;
float x3=30;
float x4=40;
float x5=50;
float result;
/* Initialize the application.
You do not need to do this more than one time. */
som_initialize();
main_som();
result=som(x1,x2,x3,x4,x5);
printf("%f", result);
som_terminate();
return 0;
}
When I run this on a raspberry-pi with
gcc -o test1 main.c
It gives me undefined references to all the functions...
Any ideas what went wrong?
You have to build it with the generated makefile (the mk file) so it links with the correct Matlab libraries - that's where those functions are defined:
$ make -f test.mk
You also need to compile the other C files along with your main.c. If main.c is in the same directory as the generated code, you should be able to just do:
gcc -o test1 *.c
If the generated code is in another directory, then you can do something like:
gcc -o test1 /path/to/code/*.c -I/path/to/code main.c

shared libraries and visibility to user's memory

When I use a shared library via dlopen, can the library code "see" memory of my process that calls dlopen? For example, I would like to pass a pointer to memory allocated by my application to the library API.
I'm on Linux/x86 if it is important.
The answer is yes, it can. Here is a simple quick example for illustration purposes.
The library code (in file myso.c):
void setInt( int * i )
{
*i = 12345;
}
The library can be built as follows:
gcc -c -fPIC myso.c
gcc -shared -Wl,-soname,libmy.so -o libmy.so myso.o -lc
Here is the client code (main.c):
#include <stdio.h>
#include <dlfcn.h>
typedef void (*setint_t)( int * );
int main()
{
void * h = dlopen("./libmy.so", RTLD_NOW);
if (h)
{
puts("Loaded library.");
setint_t setInt = dlsym( h, "setInt" );
if (setInt) {
puts("Symbol found");
int k;
setInt(&k);
printf("The int is %d\n", k);
}
}
return 0;
}
Now build and run the code. Make sure main.c and the library are in the same directory, in which we execute the following:
user#fedora-21 ~]$ gcc main.c -ldl
[user#fedora-21 ~]$ ./a.out
Loaded library.
Symbol found
The int is 12345
As one can see, the library was able to write to the memory of the integer k.

C - Undefined reference to function error with linked files

I started implementing a large program. But I ran into a massive issue. So here is very simplified code of my program. I have a separate .c file for my functions which is normal.c the main program is main.c and I have linked those two with cal.h header file.
main.c
#include <stdio.h>
#include "cal.h"
void main()
{
int num1, num2, ans;
num1=5;
num2=5;
ans=add(num1, num2);
printf("%d" ,ans);
}
normal.c
#include "cal.h"
int add(int num1, int num2)
{
return num1+num2;
}
cal.h
#ifndef CAL_H_INCLUDED
#define CAL_H_INCLUDED
#include <errno.h>
int add(int num1, int num2);
#endif // CAL_H_INCLUDED
but when I compile this, it gives out the error
..\main.c|10|undefined reference to `add'|
I'm using CodeBlocks v.13.12 in Windows 8.1 Any answer for this question is much appreciated. I tried with CodeLite as well, but the same error occurs. Thank you!
Complete compilation of the code is required in ubuntu terminal
use the following
gcc normal.c main.c -o out -lm
Code blocks have automatic linking but for that you need to have your source and header files under a project.
I had the same issue when I made individual .c & .h files and expected the IDE to link the object files but it failed. I put them under a project and it worked!
Use complete compilation of your code.
if your c codefiles main.c and normal.c are in ./src and header file cal.h is in ./inc follow below method from current dir(.)
g++ ./src/main.c ./src/normal.c -I ./inc -o main
now main is out binary file to execute.

Running luajit object file from C

From the documentation: http://luajit.org/running.html
luajit -b test.lua test.obj # Generate object file
# Link test.obj with your application and load it with require("test")
But doesn't explain how to do these things. I guess they're assuming anyone using Lua is also a C programmer, not the case with me! Can I get some help? GCC as an example.
I would also like to do the same thing except from the C byte array header. I can't find documentation on this either.
luajit -bt h -n test test.lua test.h
This creates the header file but I don't know how to run it from C. Thanks.
main.lua
print("Hello from main.lua")
app.c
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main(int argc, char **argv)
{
int status;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "require");
lua_pushliteral(L, "main");
status = lua_pcall(L, 1, 0, 0);
if (status) {
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
return 0;
}
Shell commands:
luajit -b main.lua main.o
gcc -O2 -Wall -Wl,-E -o app app.c main.o -Ixx -Lxx -lluajit-5.1 -lm -ldl
Replace -Ixx and -Lxx by the LuaJIT include and library directories. If you've installed it in /usr/local (the default), then most GCC installations will find it without these two options.
The first command compiles the Lua source code to bytecode and embeds it into the object file main.o.
The second command compiles and links the minimal C application code. Note that it links in the embedded bytecode, too. The -Wl,-E is mandatory (on Linux) to export all symbols from the executable.
Now move the original main.lua away (to ensure it's really running the embedded bytecode and not the Lua source code file) and then run your app:
mv main.lua main.lua.orig
./app
# Output: Hello from main.lua
The basic usage is as follows:
Generate the header file using luajit
#include that header in the source file(s) that's going to be referencing its symbols
Compile the source into a runnable executable or shared binary module for lua depending on your use-case.
Here's a minimal example to illustrate:
test.lua
return
{
fooprint = function (s) return print("from foo: "..s) end,
barprint = function (s) return print("from bar: "..s) end
}
test.h
// luajit -b test.lua test.h
#define luaJIT_BC_test_SIZE 155
static const char luaJIT_BC_test[] = {
27,76,74,1,2,44,0,1,4,0,2,0,5,52,1,0,0,37,2,1,0,16,3,0,0,36,2,3,2,64,1,2,0,15,
102,114,111,109,32,102,111,111,58,32,10,112,114,105,110,116,44,0,1,4,0,2,0,5,
52,1,0,0,37,2,1,0,16,3,0,0,36,2,3,2,64,1,2,0,15,102,114,111,109,32,98,97,114,
58,32,10,112,114,105,110,116,58,3,0,2,0,5,0,7,51,0,1,0,49,1,0,0,58,1,2,0,49,1,
3,0,58,1,4,0,48,0,0,128,72,0,2,0,13,98,97,114,112,114,105,110,116,0,13,102,
111,111,112,114,105,110,116,1,0,0,0,0
};
runtest.cpp
// g++ -Wall -pedantic -g runtest.cpp -o runtest.exe -llua51
#include <stdio.h>
#include <assert.h>
#include "lua.hpp"
#include "test.h"
static const char *runtest =
"test = require 'test'\n"
"test.fooprint('it works!')\n"
"test.barprint('it works!')\n";
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
// package, preload, luaJIT_BC_test
bool err = luaL_loadbuffer(L, luaJIT_BC_test, luaJIT_BC_test_SIZE, NULL);
assert(!err);
// package.preload.test = luaJIT_BC_test
lua_setfield(L, -2, "test");
// check that 'test' lib is now available; run the embedded test script
lua_settop(L, 0);
err = luaL_dostring(L, runtest);
assert(!err);
lua_close(L);
}
This is pretty straight-forward. This example takes the byte-code and places it into the package.preload table for this program's lua environment. Other lua scripts can then use this by doing require 'test'. The embedded lua source in runtest does exactly this and outputs:
from foo: it works!
from bar: it works!

making small c project

everybody out there
i write a very simple c code which is following:
#include<stdio.h>
int main()
{
int a,b,s,m,d;
system("clear");
int a =20;
int b =40;
s=sum(a,b);
m=mul(a,b);
d=div(a,b);
printf("\n the sum of given no. = %d\nThe product of given no. = %d\nThe division of given no = %d",s,m,d);
return 0;
}
the name of the file is exp.c
than i write the following code:
#include<stdio.h>
int sum( int x ,int y)
{
int z;
z=x+y;
return z;
}
i saved it as sum.c
than i write the following code :
#include<stdio.h>
int mul( int z ,int u)
{
int v ;
v=z+u;
return v;
}
save it as mul.c
than i write the following code
#include<stdio.h>
int div (int a, int b)
{
int f;
f=a/b;
return f;
}
save it as div .c
now my problem is that i want to use all file as a single project.
i want exp.c use the function defined in mul.c,div.c,sum.c
i want to know how to do this?
how to make library form mul.c,div.c,sum.c?
how to associate these library with exp.c ?
can any body explain me the detail process of making project ?
i 'm using ubuntu as my operating system. please help me
The easiest way is to not make a library, but just compile them all together into a single executable:
$ gcc -o myprogram sum.c mul.c div.c
This has the drawback that you will re-compile all the code all the time, so as the files grow large, the penalty (build time) goes up since even changing just div.c (for example) will force you to re-compile sum.c and mul.c too.
The next step is to compile them separately, and leave the object files around. For this, we can use a Makefile like so:
myprogram: sum.o mul.o div.o
sum.o: sum.c
mul.o: mul.c
div.o: div.c
This will leave the object files around, and when you type make the make tool will compare the timestamps of the object files to those of the C files, and only re-compile that which changed. Note that for the above to work, there must be a physical TAB after each colon.
There are a few steps you need to do for this:
Declare the functions in your main file When you compile your main file (exp.c) the compiler will output an error because he does not know what kind of functions sum, mul etc. are. So you have to declare them via int sum( int x ,int y); in this file. A more general approach (which is clearer) is to write all the functions you have in a file (not all, but those that will be accessed from other files) into a header file and then include the header file.
Compile each file You need to compile each file. This can be done via a simple gcc -c mul.c etc. This will create a mul.o - a machine language file.
Link them Once every file is compiled you need to put them together in one executable. This is done via gcc -o outputname mul.o sum.o ...
Note that steps 2 and 3 can also be combined, I just wanted to explain the steps clearly. This is usually done via a Makefile to speed things up a bit
Firstly, you will need to declare each of your functions in a corresponding header file (you don't have to use header files, but it's the most common way of doing this). For instance, div.h might look like:
#ifndef DIV_H_
#define DIV_H_
int div(int a, int b);
#endif
You will then to #include the header files in source files where the corresponding functions are used.
Then, to compile and link:
gcc -o my_prog exp.c sum.c mul.c div.c
As others have suggested, you make want to read up on Make, as it helps simplify the build process once your project gets more complicated.
You need to declare the functions in the file they are used. The common way to do this is to put the declarations in a header file, lets say funcs.h:
#ifndef FUNCS_H
#define FUNCS_H
int sum( int, int );
int mul( int, int );
int div( int, int );
#endif
Now #include this in your main source file. Then to build the executable:
gcc exp.c sum.c div.c mul.c
To create a library, you need to compile the files separately:
gcc -c sum.c div.c mul.c
and then run ar to build the library:
ar rvs sum.o div.o mul.o mylib.a
And then use it from gcc:
gcc exp.c mylib.a
A good practise to organize the code could be put all the functions prototypes inside a .h file, and the implementations into a related .c file, using include guards to avoid multiple inclusion.
Example module.h file:
#ifndef MODULE_NAME
#define MODULE_NAME
void module_func();
#endif
Example module.c :
#include "module.h"
void module_func(){
//implementation
}
read up on make - this will answer your questions about building/compilation/etc
You should have a .h file that will include your function prototypes. It's not strictly needed (as your functions return int) but you must get in the habit now, because it won't come easy later

Resources