Including source files in C files - c

I am very new to C, so I apologize for this newby question.
I would like to use this source code in my project: http://base64.sourceforge.net/b64.c.
So, I include it in my test file:
#include <stdio.h>
#include "b64.c"
int main()
{
return 0;
}
However, main() is defined in b64.c as well, so upon compiling, I get:
test.c:4:5: error: redefinition of ‘main’
b64.c:495:5: note: previous definition of ‘main’ was here
test.c: In function ‘main’:
test.c:5:1: error: number of arguments doesn’t match prototype
b64.c:495:5: error: prototype declaration
What is the correct usage of this source file, or any? How do we correctly use it, or use functions defined in that file?
Edit: I understand that the problem is due to the duplicate definitions of main. I know there can only be one. My question is rather, won't every meaningful project need it's main method? Then why is there a main method defined in b64.c? Are we just supposed to delete this method from the source code? It seems odd that the source code doesn't just come ready to be included and used.

It is never a good idea to #include a C source file into your code. You can either copy the code from the other C source file into your code, or include the needed prototypes in your code and make a call to the functions, linking those after compiling them separately.

you should use one of the two main functions.
If you want a new main, write your main method in your file and remove it from the 'b64.c' file, if you want to use it from the 'b64.c' file remove your (empty) main.

If main is defined in b64.c either you cannot simply redefine it in your main source file.
What do you want is to use several functions from b64.c in your program. Delete the main function from it and create a header file where you protoype all of the functions in b64.c. After that, include this header file in your main program. Have a look at this short Wikipedia entry. It should give you an overview of the topic.
Besides this: It seems that you aren't very familar with C. Try out some tutorials and go on reading about C.

First of all, you must redeclare the .c file as a .h, and then you have to go through the source code and rename any duplicate methods or global variable names. The main method is the starting point of a program so there can only be one.

(Usualy you dont include .c files, only .h)
if you want the functions inside the "b64.c" you should delete the main function from "b54.c"!

A C application needs one main() function. Your file b64.c looks like a self-sufficient C program so you don't need your test.c. Just compile and run b64.c.

When you are including that source file you are getting 2 main() declaration which is incorrect. So you have redefined "main" in this case.
Including .c into another .c file doesn't make sense. C files compile to .obj files, which are linked by the linker into the executable code , so there is no need to include one .C file into another. Instead, you can make a .h file that lists the functions and include that .h file

Related

Combine two C program files in VScode, macOS

I got two C program files, a basic code
main.c and function.c
the function.c file contains the function which I need to call in main.c file
i've tried merging files using -o
the error appears to be : liker not found, although all the libraries and stuff are perfectly present in my system.
I'am facing this problem in vsCode in macOS.
Let's begin with taking an example in the attachment there are two pictures if you see the picture which has code for one.c there I have used a line
#include "two.c"
Just to tell the compiler that I want to see every single definition in two. c
In file one.c I have called a function named print which is defined in two. c
One thing that can be noticed and is a really important observation is that in two.c, the file from where definitions needed to be called doesn't have a main function. Can you guess why? The reason is simply because when you click on one.c your system will call the main function located in one.c. Upon seeing two main functions on the second file it gets confused and throws error, and just think why you even need the main function in two.c. There is no need because we use the main function just to perform certain actions and in two.c you really don't need to perform any action but you only need a function to be exported on another file.
In your case, you need to eliminate the main function from the function .c file and in main .c just include the path of your function .c

Multiple includes of the same source files through a project is correct?

I'm trying to call a method in my main, which is declared in another file.
When I try to call it with this line of code in the Main.c:
#include "SPI3.c"
void main(void) {
initSpi();
}
it gives the following error:
SPI3.c:196:: error: (237) function "_initSpi" redefined
The function is declared in the file SPI3.c
void initSpi()
{
//CODE
}
I've researched thoroughly my code and there is no redefinition of the function, and searching through the web I've seen that the error also appears when you call a function that is not declared yet or when
you include the same file more than once and it redefines the function.
I'm certain it's the former because I actually do more than one include of this file in the project, because I also need to call those methods in other files.
What am I doing wrong? There can only be one include of a source file in the whole project? Or is there another solution? Could it be that the function is just not initialized?
Thanks, feel free to ask for more details.
By including any file, you paste its contents into your file. So, the function initSpi() is defined twice: within SPI3.c and Main.c => you get redefinition. You need to include only .h headers not .c files. These header files contain only declarations (opposed to definitions), e.g.:
/* SPI3.h */
void initSpi();
So, we include header files into our file and get declarations of functions and variables that are defined elsewhere. In order to link their definitions, we can possibly need also a Makefile or a C project file.
You should not include .c files, but .h files (except if you know exactly what you are doing).
I would rather do the following thing:
in your SPI3.h file, declare your function:
void initSpi(void);
Don't forget Include guard in your .h file
and in your main.c file:
#include "SPI3.h"
Thus your function is only defined once (in your SPI3.c file), and you will not get the redefined error.
Just for clarification
When you write the following code in your .c file:
void initSpi()
{
//CODE
}
Then you both declare and define your function.
When you write the following code in your .h file:
void initSpi(void);
Then you just declare your function. It is your function prototype.
Your function can be declared multiple times, but can only be defined once (except if using the weak keyword).
That why it is recommended to declare (and only declare) your functions in .h files and to only include those files into your .c files.

How to use a function from an object file

I'm pretty sure this question is a duplicate, but can't find an answer.
I wrote a function (in "function.h" and "function.c" files), and compiled it to "function.o" file. I want to use the function defined in "function.c" in my main source, but without including "function.h". Is that possible, to compile main.c using just "function.o"?
A header file is (usually) just a list of declarations which are inserted textually (by #include) into your source files.
Therefore, if function.h contains
void foo(int x);
and you have #include "function.h" in your main source file, it is exactly equivalent to just writing void foo(int x); in your source file.
Header files are useful for code organization because it would be highly inefficient (and error-prone) to copy those declarations by hand into every source file that used them. But, if you want to avoid the header file for any reason, copying those declarations directly into your source file has the same effect as #include'ing the file.

Include c file in another

I want to include a .c file in another. Is it possible right? It works well if I include a header file in a .c file, but doesn't work as well if I include a .c file in another .c file.
I am using Visual Studio and I get the following error:
main.obj : error LNK2005: _sayHello already defined in sayHello.obj
/* main.c */
#include "sayHello.c"
int main()
{
return 0;
}
/* sayHello.c */
#include <stdio.h>
void sayHello()
{
printf("Hello World");
}
I don't know what this error could mean. Time to ask more advanced C coders. :)
I want to include a .c file in another.
No you don't. You really, really don't. Don't take any steps down this path; it only ends in pain and misery. This is bad practice even for trivial programs such as your example, much less for programs of any real complexity. A trivial, one-line change in one file will require you to rebuild both that file and anything that includes it, which is a waste of time. You lose the ability to control access to data and functions; everything in the included .c file is visible to the including file, even functions and file scope variables declared static. If you wind up including a .c file that includes another .c file that includes another .c file und so weiter, you could possibly wind up with a translation unit too large for the compiler to handle.
Separate compilation and linking is an unequivocal Good Thing. The only files you should include in your .c files are header files that describe an interface (type definitions, function prototype declarations, macro defintions, external declarations), not an implementation.
It works, but you need to be careful with how you build the program. Also, as folks have pointed out in comments, it's generally considered a bad idea. It's unexpected, and it creates problems like these. There are few benetfits, especially for what seems like a trivial program. You should probably re-think this approach, altogether.
After doing something like this, you should only compile main.c, and not attempt to link it with the result of compiling sayHello.c, which you seem to be doing.
You might need to tell Visual Studio to exclude the latter file from the build.
Yes, any '.c' file can be included into another program.
As one include '.h' file like 'stdio.h' in the program.
After that we can call those function written into this external file.
test.c::
#include<stdio.h>
#include<conio.h>
void xprint()
{
printf("Hello World!");
}
main.c::
#include "test.c"
void main()
{
xprint();
getch();
}
Output:: Hello World!
This is a linker error. After compiling all your .c files to .obj files (done by the compiler) the linker "merges" them together to make your dll/exe. The linker has found that two objects declare the same function (which is obviously not allowed). In this case you would want the linker to only process main.obj and not sayhello.obj as well (as its code is already included in main.obj).
This is because in main.obj you will ALSO have the sayHello() function due to the include!
sayHello.h
#include <stdio.h>
void sayHello(void);
main.c
#include "sayHello.h"
int main()
{
sayHello();
return 0;
}
You probably defined two times this function
void sayHello()
{
printf("Hello World");
}
one in your current file and one in sayhello.c
You must remove one definition.
The problem seems to be that sayHello.c got compiled into an object file called sayHello.obj, and main.c (also including all the source text from sayHello.c), got compiled into main.obj, and so both .obj files got a copy of all the external symbols (like non-static function definitions) from sayHello.c.
Then all the object files were supposed to get "linked" together to produce the final executable program file, but the linking breaks when any external symbols appear more than once.
If you find yourself in this situation, you need to stop linking sayHello.obj to main.obj (and then you might not want to compile sayHello.c by itself into its own object file at all).
If you manually control every step of the build (like you might when using the CLI of your compiler), this is often just a matter of excluding that object file from the invocation of the linker or compiler.
Since you are using Visual Studio, it's probably making a bunch of assumptions for you, like "every .c file should be compiled into its own object file, and all those object files should be linked together", and you have to find a way to circumvent or disable this assumption for sayHello.c.
One easy and somewhat idiomatic solution might be to rename sayHello.c into sayHello.c.inc.
//THIS IS THE MAIN FILE//
#include "test.c"
int main()
{
multi(10);
}
//THIS IS THE TEST FILE//
#include<stdio.h>
void multi(int a)
{
printf("%d",a*2);
}
POINTS TO BE NOTED:
Here you need to run the program which contains "main()" function.
You can avoid the "stdio.h" header file in main function. Because, you are including the file which already contains the "stdio.h" header file.
You have to call the function from the "main" file.
The including file should be "file_name.c" not "file_name.h". Because usually we use .h extension for the header file. Since we are including another program file and not the header file, we have to use .c. Otherwise it will give you Fatal Error and the Compilation gets terminated.

What do .c and .h file extensions mean to C?

It's all in the title; super-simple I reckon, but it's so hard to search for syntactical things anywhere.
These are two library files that I'm copying from CS50.net, and I'm wondering why they have two different extensions.
.c : c file (where the real action is, in general)
.h : header file (to be included with a preprocessor #include directive). Contains stuff that is normally deemed to be shared with other parts of your code, like function prototypes, #define'd stuff, extern declaration for global variables (oh, the horror) and the like.
Technically, you could put everything in a single file. A whole C program. million of lines. But we humans tend to organize things. So you create different C files, each one containing particular functions. That's all nice and clean. Then suddenly you realize that a declaration you have into a given C file should exist also in another C file. So you would duplicate them. The best is therefore to extract the declaration and put it into a common file, which is the .h
For example, in the cs50.h you find what are called "forward declarations" of your functions.
A forward declaration is a quick way to tell the compiler how a function should be called (e.g. what input params) and what it returns, so it can perform proper checking (for example if you call a function with the wrong number of parameters, it will complain).
Another example. Suppose you write a .c file containing a function performing regular expression matching. You want your function to accept the regular expression, the string to match, and a parameter that tells if the comparison has to be case insensitive.
in the .c you will therefore put
bool matches(string regexp, string s, int flags) { the code }
Now, assume you want to pass the following flags:
0: if the search is case sensitive
1: if the search is case insensitive
And you want to keep yourself open to new flags, so you did not put a boolean.
playing with numbers is hard, so you define useful names for these flags
#define MATCH_CASE_SENSITIVE 0
#define MATCH_CASE_INSENSITIVE 1
This info goes into the .h, because if any program wants to use these labels, it has no way of knowing them unless you include the info. Of course you can put them in the .c, but then you would have to include the .c code (whole!) which is a waste of time and a source of trouble.
Of course, there is nothing that says the extension of a header file must be .h and the extension of a C source file must be .c. These are useful conventions.
E:\Temp> type my.interface
#ifndef MY_INTERFACE_INCLUDED
#define MYBUFFERSIZE 8
#define MY_INTERFACE_INCLUDED
#endif
E:\Temp> type my.source
#include <stdio.h>
#include "my.interface"
int main(void) {
char x[MYBUFFERSIZE] = {0};
x[0] = 'a';
puts(x);
return 0;
}
E:\Temp> gcc -x c my.source -o my.exe
E:\Temp> my
a
They're not really library files. They're just source files. Like Stefano said, the .c file is the C source file which actually uses/defines the actual source of what it merely outlined in the .h file, the header file. The header file usually outlines all of the function prototypes and structures that will be used in the actual source file. Think of it like a reference/appendix. This is evident upon looking at the header file, as you will see :) So then when you want to use something that was written in these source files, you #include the header file, which contains the information that the compiler will need to know.
The .c is the source file and .h is the header file.
The .c files are source files which will be compiled. The .h files are used to expose the API of a program to either other part of that program or other program is you are creating a library.
For example, the program PizzaDelivery could have 1 .c file with the main program, and 1 .c file with utility functions. Now, for the main part of the program to be able to use the utility functions, you need to expose the API, via function prototype, into a .h file, this .h file being included by the main .c file.
.c : 'C' source code
.h : Header file
Usually, the .c files contain the implementation, and .h files contain the "interface" of an implementation.

Resources