Is it possible to include functions from .c file without compiling it? - c

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);

Related

Macro does not reach .c file

I am trying to enable a set of functions from a header only if a macro is defined
I define the macro before including anything and it reaches the .h file and highlights the proper functions, but it does not reach the .c file so I can call the functions with the right prototypes but they have no definition since the .c file does not see I defined the macro
Is there some way to get this to work without having to stuff all of the .c code inside the .h file?
example:
test.h:
#ifdef _ENABLE_
int enabled_function(int a, int b);
#endif
test.c:
#ifdef _ENABLE_
int enabled_function(int a, int b)
{
return a + b;
}
#endif
main.c:
#define _ENABLE_
#include "test.h"
int main()
{
printf("%d", enabled_function(10, 10));
}
you need to use conditional compilation in both header and C file
in header file:
#define SOMETHING
#ifdef SOMETHING
int a(int);
int b(int);
int c(int);
#endif
In the C file:
#include "header_file_with_SOMETHING_declaration.h"
#ifdef SOMETHING
int a(int x)
{
/* ... */
}
int b(int x)
{
/* ... */
}
int b(int x)
{
/* ... */
}
#endif
Your source files test.c and main.c represent separate translation units. The macro definitions declared in one are not visible to the other.
Declarations that need to be visible across multiple translation units, whether of macros or of anything else, generally should go into header files that all translation units wanting them #include. It is possible to have a header that serves the sole purpose of defining macros that control configuration options, that you would create or update prior to compilation. There are tools that automate that sort of thing, but they are probably much heavier than you require for your purposes right now.
For macros specifically, most compilers also offer the option of specifying macro definitions via compiler command-line arguments.
Either way, no, your definition in main.c of macro _ENABLE_ will not be visible in test.c. (And no, you shouldn't merge test.c into test.h.)
But you should also consider whether you actually need any of that. Certainly there are use cases for cross-translation-unit build-time configuration, but what you present does not look like one of them. It is rarely very useful to suppress the compilation of a function just because you know you're not going to call it. it is usually better to either remove it altogether or to leave it, uncalled. In the latter case, your linker might even be smart enough to omit unused functions from the final binary.
"Is there some way to get this to work without having to stuff all of the .c code inside the .h file?"
and from comments...
"...but I wish to be able to define the macro in my main file and have it be visible from the .c file too
So, you are asking to #include one .c file into another .c file. This is doable with caution. But because a .c file containing the main() function cannot be #include into another .c file without invoking a multiply defined symbol error for main(...), it has to be the other way around. That is a dedicated .c file (eg. enabled.c) could be created that contains all of the #defines function prototypes and definitions. This .c file can then be #included into main.c to hopefully satisfy a variation of what you are looking for.
Following is tested source code that does this:
enable.c
#define _ENABLE_
//test criteria - then create prototype of enabled_function
#ifdef _ENABLE_
static int enabled_function(int a, int b);
#endif
#ifdef _ENABLE_
static int enabled_function(int a, int b)
{
return a + b;
}
#endif
static int use_enabled_function(int a, int b);
//This will be created with or without _ENABLE_, but its
//definition changes based on whether _ENABLE_ exists or not.
static int use_enabled_function(int a, int b)
{
#ifdef _ENABLE_
return enabled_function(a, b);
#elif
return -1;
#endif
}
main.c
#include "enable.c"
int main(void)
{
//test criteria - then use enabled_function
#ifdef _ENABLE_ //must include test for existence before using
printf("%d\n", enabled_function(10, 10));
#endif
//no need to test criteria here (tested internally)
printf("%d\n", use_enabled_function(10, 10));
return 0;
}

How to create a single C source file that includes two header files?

Is there a way to setup a single project with different configurations (or a different method) that point to the unique header files.
I want to create a single C project that contains two header files (e.g header1.h and header2.h). In my .c source file I have defined two configurations. e.g:
int main()
{
#ifdef _print1_
#include "header1.h"
#elif _print2_
#include "header2.h"
#endif
return 0;
}
Now for example I want to just print any string as output. So what I want to declare in my header file. That is #ifdef print1 needs to execute header1.h and #elif print2 needs to execute header1.h .Please note that I need to have a header file in different folders with the same file name.
Can you please any one assist me on this?
If you do it, do it this way:
#ifdef _print1_
# include "header1.h"
#elif _print2_
# include "header2.h"
#endif
int main(void)
{
...
return 0;
}

Should ANSI C function definition be placed inside header (.h) or source (.c) file?

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.

Standard libraries included multiple times over several files?

In the K&R book (p59) (edit: second edition, covering ANSI C), it is suggested that it is easier to split larger projects into multiple files. In each file, several libraries are included at the top as usual: e.g. getop.c needs stdio.h, and so does stack.c and so does main.c.
The snippets are something like this:
//main.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
int main(void)
{
//etc
}
//getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"
getop()
{
/*code*/
}
//stack.c
#include <stdio.h>
#include "calc.h"
void push(double val)
{
//code
}
I am having trouble figuring out how including the standard libraries several times in a project works. Of course, for the custom .c files to be able to access built in functions, we need to include #include <header.h> so that they are aware of the existence of printf() and getchar() and so on, but wouldn't this approach increase the size of the final program if stdio.h is included four times instead of once ( if everything was placed in one file)?
K&R does point out that splitting a program over several files eventually makes it more difficult to maintain all the .h files.
I suppose what I am really asking is how does the compiler figure out the problem of one library being #included several times in a project.
I have read up on using include guards, but it seems that is not needed for this implementation, as they deal with ensuring that identical bits of code aren't included twice, as in:
File "module.h"
#ifndef MODULE_H
#define MODULE_H
struct foo {
int member;
};
#endif /* MODULE_H */
File "mod2.h"
#include "module.h"
File "prog.c"
#include "module.h"
#include "mod2.h"
refs
I suppose what I am really asking is how does the compiler figure out the problem of one library being #included several times in a project.
you don't include a library by #include <stdio.h>, you just include it's declarations, so the compiler knows what functions exists. The linker takes care of including a library and putting everything together.
Because they use something called include guards, suppose your own include files where to be included more than once, then you can do this
MyHeader.h
#ifndef MY_HEADER_H
#define MY_HEADER_H
/* file content goes here */
#endif /* MY_HEADER_H */
Then you have another header
**AnotherHeader.h**
#ifndef MY_ANOTHER_HEADER_H
#define MY_ANOTHER_HEADER_H
#include "MyHeader.h"
/* file content goes here */
#endif /* MY_ANOTHER_HEADER_H */
and in your program
main.c
/*
* MY_HEADER_H is undefined so it will be defined and MyHeader.h contents
* will be included.
*/
#include "MyHeader.h"
/*
* MY_HEADER_H is defined now, so MyHeader.h contents will not be included
*/
#include "AnotherHeader.h"
int main()
{
return 0;
}
Since the included files are only included once per compilation unit the resulting binary size will not increase, besides the inclusion of header files only increases the compiled file size when for example there are string literals declared in those headers, otherwise they only provide information to the compiler about how to call a given function, i.e. how to pass parameters to it and how to store it's returned value.

include function definitions present in .c files in main

I had to write few functions which are very long. So, I decided to put them in different files and link them to main.. so that it works as if I wrote function definitions after main().
How do I do it..
In a .h file you put your prototype
#ifndef MY_HEADER_H
#define MY_HEADER_H
void hello(void);
#endif
In a seperate .c file you implement your function such as hello.c
#include "myheader.h"
void hello()
{
printf("Testing function from other file\n");
}
then in main you do
#include "myheader.h"
int main()
{
hello();
return 0;
}
make sure you compile hello.c into hello.o before linking the files or it will tell you that it can't resolve the reference to hello.
Find create a header file that has a file ending of .h .
Lets say this header file is named blah.h.
The general structure of this header will be
#ifndef BLAH_H_INCLUDED
#define BLAH_H_INCLUDED
//code
#endif // BLAH_H_INCLUDED
Those are header guards, to prevent multiple inclusions.
Inside the code you will still your function declarations.
For example, void function(int blah); would be a valid function declaration.
This file is then included at the top of all of your files that uses or defines the functions declared, #include "blah.h"
Then you can define your functions in the other files, and when you link them together the program will work.

Resources