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
Related
Taking the following program as an example:
// myprogram.c
#include<stdio.h>
int a, b;
int main(void)
{
printf("A: %d\n", a);
printf("B: %d\n", b);
}
// friendsprogram.c
int a=1;
static int b=2;
$ gcc myprogram.c friendsprogram.c -o out; ./out
A: 1
B: 0
How would the translation units be classified in the above? And how what that be different than just the contents of the file "myprogram.c" and "friendsprogram.c"? Does the translation unit ever depend on the command that is issued to the compiler? For example, If I change the command to just:
$ gcc myprogram.c -o out; ./out
My output becomes:
A: 0
B: 0
A translation unit is a source file along with all of its included headers that is compiled as a single unit.
In this example, myprogram.c along with the header stdio.h is one translation unit. The file friendsprogram.c is another translation unit.
Note that this doesn't change when you compile like this:
gcc myprogram.c friendsprogram.c -o out
Because this command line combines compiling and linking into a single step. A temporary object file is created for myprogram.c and another for friendsprogram.c, then those object files are linked to create the file "out".
What's happening is a side effect of old lenient compiler/linker behavior and a so-called "common" section.
int a;
The C spec says this global-scope variable is initialized to zero. You would expect this to go into the .bss (zero-initialized data) section of the executable.
But in GCC <10, the variable is put into the "common" section when that file (translation unit) is compiled.
int a=1;
Now you've provided an initialization, and this variable will go into the .data section.
But when the linker links these two object files together, rather than issue a "multiple definitions" (for the same name) error, it will do something controversial, and merge them into one variable, due to the common section semantics.
By passing -fno-common, or using GCC >= 10, the common section is not used, and the linker will issue an error and refuse to link your program.
So what should you do? Simple: provide only one definition for any name.
If you really want to use global variables (undesirable in general), and you want to put them in a separate translation unit (weird), use extern in your other files:
data.h
// Declaration: Tells everyone that 'a' exists somewhere
extern int a;
data.c
#include "data.h"
// Definition: defines the variable and its initial value
int a = 42;
main.c
#include <stdio.h>
#include "data.h"
int main(void)
{
printf("a = %d\n", a);
}
For my program I am linking 3 files in total. A main.c, sortfile.c and my.h(header file). For my sortfile.c I am implementing a OddEven Sort. I am unsure whether my coding algorithm is correct. Also would like to know what information usually goes in a header file. Is it only the other two c files vide #include?
#include <stdio.h>
void swap(int *, int *);
void Odd_Even_Sort(int *);
/* swaps the elements */
void swap(int * x, int * y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
/* sorts the array using oddeven algorithm */
void Odd_Even_Sort(int * x)
{
int sort = 0, i;
while (!sort)
{
sort = 1;
for (i = 1;i < MAX;i += 2)
{
if (x[i] > x[i+1])
{
swap(&x[i], &x[i+1]);
sort = 0;
}
}
for (i = 0;i < MAX - 1;i += 2)
{
if (x[i] > x[i + 1])
{
swap(&x[i], &x[i + 1]);
sort = 0;
}
}
}
I did not include a main in the sortfile.c because I intended to put main in the main.c file.
You look confused. Read first the wikipage on linkers and on compilers. You don't link source files, but only object files and libraries.
(I am guessing and supposing and hoping for you that you are using Linux)
You also compile translation units into object files.
Header files are for the preprocessor (the first "phase" of the compilation). The preprocessing is a textual operation. See this answer for some hint.
So you probably want to compile your main.c into main.o with
gcc -Wall -g -c main.c -o main.o
(the -Wall asks for all warnings, so never forget that; the -g asks for debugging information; -c asks to compile some source into some object file; order of program arguments to gcc matters a big lot).
Likewise, you want to compile your sortfile.c into sortfile.o. I leave as an exercise to get the right command doing that.
Finally, you want to get an executable program myprogsort, by linking both object files. Do that with
gcc -g main.o sortfile.o -o myprogsort
But you really want to use some build automation tool. Learn about GNU make. Write your Makefile (beware, tabs are important in it). See this example. Don't forget to try make -p to understand (and take advantage of) all the builtin rules make is knowing.
Also would like to know what information usually goes in a header file.
Conventionally you want only declarations in your common header file (which you would #include in every source file composing a translation unit). You can also add definitions of static inline functions. Read more about inline functions (you probably don't need them at first).
Don't forget to learn how to use the gdb debugger. You probably will run
gdb ./myprogsort
more than once. Don't forget to rebuild your thing after changes to source code.
Look also inside the source code of some medium sized free software project coded in C on github. You'll learn a big lot.
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
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
I’m trying to create ./configure + make set for building C codes in following structure by using autotools. drive.c uses function in mylib.c
[mylib]
+mylib.c
+mylib.h
[src]
+drive.c
More details are here.
[mylib.c]
#include <stdio.h>
#include "mylib.h"
int main(){
mylib();
return 0;
}
void
mylib(void)
{
printf ("Hello world! I AM mylib \n");
}
[mylib.h]
void mylib(void);
[drive.c]
#include <mylib.h>
int
main (int argc, char **argv)
{
mylib();
return 0;
}
Actually I’ve given main() both mylib.c and drive.c.
If I make them on CentOS process is noremally finished however If I make them on MINGW an error message multiple definition ofmain'` is shown
How can I make them on MINGW even if they have multiply have main()?
And those followings are config files for autotools.
[confiugre.ac]
AC_PREREQ([2.69])
AC_INIT([libmylib], [1], [admin#localhost])
AC_CONFIG_SRCDIR([mylib/mylib.c])
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_MACRO_DIR([m4])
AM_INIT_AUTOMAKE([foreign])
LT_INIT
AC_PROG_CC
AC_CONFIG_FILES([mylib/Makefile
src/Makefile
Makefile])
AC_OUTPUT
[Makefile.am]
SUBDIRS = mylib src
ACLOCAL_AMFLAGS = -I m4
[Makefile.am#src]
bin_PROGRAMS = drive
drive_SOURCES = drive.c
LDADD = ../mylib/libmylib.la
AM_CPPFLAGS = -I../mylib
[Makefile.am#mylib]
lib_LTLIBRARIES = libmylib.la
libmylib_la_SOURCES = mylib.c
include_HEADERS = mylib.h
You are confusing things, the idea of having multiple main() is fundamentally wrong. Libraries never ever contain a main() function.
(With the exception of Windows DLLs that contain a DllMain, but that means something different.)
If you want to provide a test case for your library, you make the test case as a separate project which includes the library. The test code should not be inside the library itself, neither should main().
Also, I very much doubt you are able to build a program with several function definitions that have the same name, be it main() or something else. If you believe you have managed this, I would either suspect that you haven't linked the files correctly, or that the linker is crap.