Include c file in another - c

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.

Related

How to combine assembly functions in .h file?

Might be a duplicate but i wasn't able to find a answer for my question.
Usually if you want to import multiple functions from different c files in one main class, one would make a .h file and list up all functions from the .c sources.
My problem is, that all functions are wridden in .asm files. I used extern void asmFunc(int i, char c); to use the function in further code, but they become more and more and i don't want to end up with 200 of those extern lines at the beginning of my main. How can i create a library.h with all assembly functions so i can just write #include "library.h" at the beginning of my main class?
EDIT:
I think i didn't give enough specific information:
I use MINGW gcc and NASM to compile c and asm files
I have to compile all files to .o first so i can match them
The first answer i got didn't work because my compile chain is a bit complicated thanks to the restrictions i have on Windows (i want Linux back)
It looks like this:
I got a folder containing three folders with seperated library-like structures: bwt (basic window toolkit), io and std (stuff like strlen)
They are compiled into bwt.o io.o and std.o.
Now i want to make a .h file for each of them so i can #include "bwt.h" in all kernel classes which need them. How do i get gcc to realize, that all functions in bwt.h are defined in bwt.o?
Since you have a .o file, it doesn't matter that the source for those routines is assembly. As long as you know how to call them as C functions that's what matters.
So put all of your extern declarations for the assembly functions in library.h, then #include "library.h" in your main file. Then you can link them.
gcc -c main.c
gcc -o program main.o asmfunctions.o
You can:
Make a file
Save the file as library.h (same folder as your C file)
Put your extern declarations* in the file
Add #include "library.h" in your C file
#include is literally copy-paste. You can put some code into another file, and then you can #include that file, and the compiler pretends you wrote the code in the main file directly. That's how it works.
* by the way, you don't need to write extern when declaring functions - only variables.

Including source files in C files

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

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.

Separating a group of functions into an includable file in C?

I know this is common in most languages, and maybe in C, as well. Can C handle separating several functions out to a separate file and having them be included?
The functions will rely on other include files, as well. I want the code to retain all functionality, but the code will be reused in several C scripts, and if I change it once I do not wish to have to go through every script and change it there, too.
Most definitely! What you're describing are header files. You can read more about this process here, but I'll outline the basics below.
You'll have your functions separated into a header file called functions.h, which contains the following:
int return_ten();
Then you can have a functions.c file which contains the definition of the function:
int return_ten()
{
return 10;
}
Then in your main.c file you can include the functions.h in the following way:
#include <stdio.h>
#include "functions.h"
int main(int argc, char *argv[])
{
printf("The number you're thinking of is %d\n", return_ten());
return 0;
}
This is assuming that your functions.h file is in the same directory as your main.c file.
Finally, when you want to compile this into your object file you need to link them together. Assuming you're using a command-line compiler, this just means adding the extra definition file onto the end. For the above code to work, you'd type the follow into your cmd: gcc main.c functions.c which would produce an a.out file that you can run.
Declare the functions in header files and then implement them in .c files. Now you can #include the header files into any program that uses the functions and then link the program against the object files generated from the .c files.
Say you have a file with a function that you want to use elsewhere:
int func2(int x){
/*do some stuff */
return 0;
}
what you would do is split this up into a header file and a source file. In the header file you just have the function declaration, this tells the compiler that that function does exist, even if it is in a different file. The header might be called func2.h might look like this:
#ifndef HEADER_FUNC2_H
#define HEADER_FUNC2_H
int func2(int x);
#endif /*HEADER_FUNC2_H*/
The #ifndef HEADER_FUNC2_H part is to make sure that this only gets used once so that there are no multiple definitions going on.
then in the source func2.c file you have the actual function itself:
int func2(int x){
/*do some stuff */
return 0;
}
and in any other file now that you use func2 you have to include the header. You do this with #include "func2.h". So for example if we wanted to call func2 from randomfile.c it would be like this:
#include "func2.h"
/* rest of randomfile.c */
func2(1);
Then the last step is to link the object file that contains the function with the compiler when you compile.
If you want to reuse functions across multple programs, you should place them in a library and link it with the rest of your code.
If you want to share the same definitions (e.g. macros, types, ...) you can place them in a header file and include them with #include.
Please refrain from directly "#include" function code into a source file, it's a bad practice and can lead to very problematic situations (especially if you are a beginner, as your tag suggests).
Consder that normally when you have a set of functions you want to share and reuse, you will need both! You will usually end up with a myfuncs.lib (or libmyfuncs.a) library and a myfuncs.h header.
In the programs where you want to reuse your existing functions, you will include the header and link against the library.
You can also look at how to use dynamic libraries once you have mastered the usage of static libraries.

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