How can I create a C library in CodeBlocks that can be define and used like a standard library with the #include command?
In fact I want to create a simple library that is Composed of several functions.
Basically, you need a .h file for the header definitions and a .c containing the source code.
An example:
/* command.h */
#ifndef COMMAND_H
#define COMMAND_H
int func(void);
#endif /* COMMAND_H */
/* command.c */
#include "command.h"
int func(void)
{
return 0;
}
/* main.c */
#include <stdio.h>
#include "command.h"
int main(void)
{
printf("%d\n", func());
return 0;
}
ifndef is used to prevent the file from being included more than once.
Compile it including both .c files in the command line:
gcc -o demo main.c command.c
Or in your case, follow this guide to compile multiple files in codeblocks.
Related
In a CLion project, I have two C-language source files, "main.c" and "list.c".
The source file "main.c" has this:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
The source file "list.c" has this:
#include <stdio.h>
int printFoo() {
printf("I want Krabby Patties!\n");
return 0;
}
Now how do I call printFoo() from the main() function? I know I cannot do an include<list.c> in main.c since that will cause a multiple definitions error.
CLion uses CMake for organizing and building project.
CMakeLists.txt contains instructions for building.
Command add_executable(program main.c list.c) creates executable with files main.c and list.c. Add all source files to it. You can add headers, but it isn't necessary.
Header files contain definitions of functions and other things, source files for realization, but you can merge them.
main.c
#include "list.h"
int main() {
printFoo();
return 0;
}
list.h
#pragma once
int printFoo();
list.c
#include "list.h"
#include <stdio.h>
int printFoo(){
return printf("I want Krabby Patties!\n");
}
#pragma once tels compiler to include header file once. If you have more than one include of one file without #pragma once, you'll catch an error.
You can create one header file "list.h"
#ifndef __LIST_H__
#define __LIST_H__
int printFoo();
#endif
Then include it in main.c:
#include <stdio.h>
#include "list.h"
int main() {
printf("Hello, World!\n");
printFoo();
return 0;
}
What are advantages and disadvantages of both approaches?
Source vs. header implementation
Function definition inside source file
Header file sourcefunction.h contains declaration only.
#ifndef SOURCEFUNCTION_H
#define SOURCEFUNCTION_H
void sourcefunction(void);
#endif // SOURCEFUNCTION_H
Source file sourcefunction.c contains definition
#include "sourcefunction.h"
#include <stdio.h>
void sourcefunction(void) { printf(" My body is in a source file\n"); }
Function definition inside header file
Header file headerfunction.h contains definition which is the declaration at the same time.
#ifndef HEADERFUNCTION_H
#define HEADERFUNCTION_H
#include <stdio.h>
void headerfunction(void) { printf(" My body is in a header file\n"); }
#endif // HEADERFUNCTION_H
No source file is needed.
Consumer
File main.c
#include "sourcefunction.h"
#include "headerfunction.h"
int main(void) {
sourcefunction();
headerfunction();
return 0;
}
Why compile many source files?
We have to compile all source files and remember about them during linking.
gcc -c sourcefunction.c
gcc -c main.c
gcc main.o sourcefunction.o
Make can handle file managing but why even bother?
Is separation of interface and implementation always an issue?
It is obvious reason for big projects and teamwork. The designer specifies the interface. The programmers implement functionality.
What about smaller projects and non-formal approach?
Is removing definition from header files always preventing from linker errors?
Let's assume my program is using another module that defines the function with the same name sourcefunction().
#include "sourcefunction.h"
#include "sourcefunction1.h"
#include "headerfunction.h"
int main(void) {
headerfunction();
sourcefunction();
return 0;
}
Different function interface
File sourcefunction1.h
#ifndef SOURCEFUNCTION1_H
#define SOURCEFUNCTION1_H
int sourcefunction(void);
#endif // SOURCEFUNCTION1_H
File sourcefunction1.c
#include "sourcefunction1.h"
#include <stdio.h>
int sourcefunction(void) { int a = 5; return a; }
By compiling main.c, I get a nice compiler error
sourcefunction1.h:4:5: error: conflicting types for 'sourcefunction'
showing me the location of error.
Same function interface
File sourcefunction1.h
#ifndef SOURCEFUNCTION1_H
#define SOURCEFUNCTION1_H
void sourcefunction(void);
#endif // SOURCEFUNCTION1_H
File sourcefunction1.c
#include "sourcefunction1.h"
#include <stdio.h>
void sourcefunction(void) { int a = 5; printf("%d",a); }
Compiler does not mind multiple declarations. I get ugly linker error.
Can header implementation serve as library?
jschultz410 says
If you are writing a library and all your function definitions are in headers, then other people who do segment their development into multiple translation units will get multiple definitions of your functions if they are needed in multiple translation units
Lets' have
File consumer1.c
#include "headerfunction.h"
void consume1(void) { headerfunction(); }
File consumer2.c
#include "headerfunction.h"
void consume2(void) { headerfunction(); headerfunction();}
File twoConsumers.c
extern void consume1(void);
extern void consume2(void);
int main(void) {
consume1();
consume2();
return 0;
}
Let's compile sources.
gcc -c consumer1.c
gcc -c consumer2.c
gcc -c twoConsumers.c
So far, so good. Now, linking.
gcc consumer1.o consumer2.o twoConsumers.o
Linker error: multiple definition of 'headerfunction', of course.
But I can make my library function static.
File headerfunction.h, afterwards.
#ifndef HEADERFUNCTION_H
#define HEADERFUNCTION_H
#include <stdio.h>
static void headerfunction(void) { printf(" My body is in a header file\n"); }
#endif // HEADERFUNCTION_H
It hides the definition from other translation units.
I shouldn't answer this, but I will.
This can create duplicate definitions unless you really only have a single .c file in your project (unwise). Even the header guards won't prevent files the headers from being included multiple times if those multiple times are with different .c files. When the .obj files are linked together, there will be conflicts.
If only the function declaration and not definition is in the header, then only changes to the interface (the function name, parameters or return type) require recompiling dependencies. However, if the entire definition is in the header, then any change to the function requires recompiling all .c and .h files that depend on it, which, in a larger project, can create a lot of unnecessary recompiling.
It's not the convention. Libraries will not use this convention, so you'll be stuck dealing with their header file structure. Other developers will not use this convention, so you can create confusion or annoyance there.
This is my code. I have file1.c and file2.c. I want to call the MESSAGE from file2.c but I can't seem to do it. I am newbie in C so I really don't know what to do. I researched already but, I can't seem to find a specific answer. Thankyou.
#define MESSAGE "this is message!"
helloworld(){
printf("%s",MESSAGE);
getch();
}
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "file2.c"
int main(void)
{
helloworld();
}
There are a few misconceptions you have: First of all the concept of "calling" a macro. It's not possible, even if a macro looks like a function it's not a function and macros are not actually handled by the compiler. Instead macros are part of a separate language that is handled by a preprocessor, which takes the source file and modifies it to generate a translation unit that the compiler sees. (For more information about the difference phases of "compilation" see e.g. this reference.)
The preprocessor does this by basically doing a search-replace in the input source file: When it sees a macro "invocation" it simply replaces that with the "body" of the macro. When it sees an #include directive, it preprocesses the file and then puts the content in place of the directive.
So in your code, when the preprocessor sees the macro MESSAGE it is literally replaced by "this is message!". The actual compiler doesn't see MESSAGE at all, it only sees the string literal.
Another misconception is how you use the #include directive. You should not use it to include source files. Instead you compile the source files separately (which creates object files) and then link the generated object files together with whatever libraries are needed to form the final executable.
To solve the problem of macros (and other declarations) being available to all source files, you use header files. These are like source files, but only contains declarations and macros. You then include the header file in both source files, and both source files will know about the declarations and macros available in the header file.
So in your case you should have three files: The main source file, the source file containing the function, and a header file containing the macro and the function declaration (also known as a prototype). Something like
Header file, e.g. header.h:
// First an include guard (see e.g. https://en.wikipedia.org/wiki/Include_guard)
#ifndef HEADER_H
#define HEADER_H
// Define the macro, if it needs to be used by all source files
// including this header file
#define MESSAGE "this is message!"
// Declare a function prototype so it can be used from other
// source files
void helloworld();
#endif
Main source file, e.g. main.c:
// Include a system header file, to be able to use the `printf` function
#include <stdio.h>
// Include the header file containing common macros and declarations
#include "header.h"
int main(void)
{
// Use the macro
printf("From main, MESSAGE = %s\n", MESSAGE);
// Call the function from the other file
helloworld();
}
The other file, e.g. hello.c:
// Include a system header file, to be able to use the `printf` function
#include <stdio.h>
// Include the header file containing common macros and declarations
#include "header.h"
void helloworld(void)
{
printf("Hello world!\n");
printf("From helloworld, MESSAGE = %s\n", MESSAGE);
}
Now, if you use a command-line compiler like gcc or clang then you can simply build it all by doing e.g.
$ gcc -Wall main.c hello.c -o myhello
That command will take the two source files, main.c and hello.c and run the preprocessor and compiler on them to generate (temporary) object files. These object files are then linked together with the standard C library to form the program myhello (that's what the option -o does, names the output file).
You can then run myhello:
$ ./myhello
From main, MESSAGE = this is message!
Hello world!
From helloworld, MESSAGE = this is message!
In your file1.c, MESSAGE is a preprocessor macro, which means the text MESSAGE will be replaced with the string "this is message!". It is not visible outside the file. This is because in C, translation units are the final inputs to the compiler, and thes translation units already have all of preprocessor macros replaced by the tokens of the corresponding argument.
If you want to have a common variable, you should declare the variable as extern in a .h header file, and then #include the file where you need to use it.
see Compiling multiple C files in a program
You have to put your #define in a .h file and include it in .c files where you want to use it.
You can write the files as below and compile the code as i mention in the following steps.
file1.h
#ifndef _FILE1_H
#define _FILE1_H
#define MESSAGE "this is message!"
extern void helloworld();
#endif
file1.c
#include "file1.h"
helloworld()
{
printf("%s",MESSAGE);
getch();
}
file2.c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "file1.h"
int main(void)
{
helloworld();
return 0;
}
For compiling,
gcc -Wall file1.c file2.c -o myprog
./myprog
Here is code try this:
In File1.C
#define FILE1_C
#include "file1.h"
helloworld()
{
printf("%s",MESSAGE);
getch();
}
In File2.C
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "file1.h"
int main(void)
{
helloworld();
}
In File1.h
#ifdef FILE1_C
#define MESSAGE "this is message!"
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN helloword()
I have the next single C code and I'm trying to compile for arm using arm-gcc GNU and eclipse.
main.h
#ifndef
#define MAIN_H_
extern int rmain(int,int);
#endif
main.c
#include main.h
#include sum.h
int rmain(a1,a2){
int z=0x89;
return sum(a1+a2)+z;
sum.h
#ifndef
#define SUM_H_
extern int sum(int,int);
#endif
sum.c
#include sum.h
int sum(int a1,int a2)
return a1+a2;
My linker script file look like on this way:
mem.lds
ENTRY(rmain)
SECTIONS:{
.=0x808080
.text:{*(.text)}
.data:{*(.data)}
.bss:{*(.bss)}
}
This work OK, but my problem is that I need that function rmain will be set at 0x808080 address, so How i can do it this ?
I tryed with:
SECTIONS:{
.=0x808080
.start:{main.o (.text)}
.text:{*(EXCLUDE_FILE(main.o).text)}
.data:{*(.data)}
.bss:{*(.bss)}
}
But not luck linker say: multiple definition of rmain.
I am restricted by very specific (and rather senseless...) filing system and I can't create header files or split existing files into files holding only functions and only execution calls. I can only create .c files that can be executed and have some sort of output.
A lot of code can be reused but I am being forced to copy some functions from file to file.
Is it possible to cure this mess by including but not compiling one or more file or omitting some functions in the included files? Maybe adding some debugging into the mix can allow to compile only part of included files?
Put the shared code like this, so that it can compile on it's own and at the same time you can include it from other .c files without getting duplicate main functions:
// shared.c
#ifndef SHARED_C
#define SHARED_C
#if __INCLUDE_LEVEL__ == 0
# include <stdio.h>
# include <stdlib.h>
int main() {
fprintf(stderr, "shared file, not to run!\n");
return EXIT_FAILURE;
}
#endif
int shared_func() { return 1; }
#endif
And use it from other files
#include "shared.c"
int x = shared_func();
Can you use the pre-processor? Something like:
// this is file1.c
int Foo(int bar);
#ifndef HEADERS
int Foo(int bar)
{
return 42;
}
#endif
and
// this is file2.c
#define HEADERS
#include "file1.c"
Foo(42);