I'm new to C and programming.
I'm on Windows 10, I just installed Dev-C++ and I'm learning how to call functions from other files: i wrote this function to sum two numbers, and I call it from the main script.
The problem is that when i compile the func.c file I get the error in title, so if I run the main file it doesn't recognize the "sum" function.
This is the main.c file:
#include <stdio.h>
#include "func.h"
main(){
int x,y,s;
scanf("%d %d",&x,&y);
s = sum(x,y);
printf("\n%d",s);
}
This is the header file:
#ifndef FUNC_H_INCLUDED
#define FUNC_H_INCLUDED
int func(int a, int b);
#endif // FUNC_H_INCLUDED
And this is the code of the sum function in a func.c file:
#include <stdio.h>
#include "func.h"
int func(int a, int b){
return(a+b);
}
I did read lots of other questions, but they didnt help in my case, or I didnt get the tricky answer.
Thank you.
In case you are using Embarcadero's Dev-C++. I use their free compiler since it is "portable".
func.c and func.h both contain a function called func while your main file has a function called sum, you must have a consistency in the names, you can do s=func(x,y) and that should work, but a good practice is doing the opposite and replace func in other files by sum.
And you must compile the 3 files, compiling 1 or 2 isn't enough.
To compile them using Embarcadero's free compiler:
C:\path\to\compiler\bcc32x func.c func.h main.c
It will give you main.exe that you can run from the command prompt.
Related
I recently looked into defining functions using a header file in C.
I followed a tutorial online, but I have come across an issue:
If I use command prompt and run the executable file I created in my project folder, it takes the input from my main.c file and passes it through the function like I expected it to.
The command that I typed in Command Prompt was:
gcc matrix_product.c main.c
Within main I can call the function (which I named matrix_product), and it recognizes it. When I try to build it inside CodeBlocks, however, the compiler indicates 2 errors:
undefined reference to 'matrix_product'
error: ld returned 1 exit status
This is the code:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "matrix_product.h"
#define N 3
int main()
{
int i,j;
int m[N][N]={
{1,2,3},
{4,5,6},
{7,8,9}
};
matrix_product(m,3);
for(i=0;i<N;i++){
if(i==1){printf("M^2 = ");
}else{printf(" ");}
for(j=0;j<N;j++){
printf("%d ",m[i][j]);
}
printf("\n");
}
return 0;
}
matrix_product.c
#include <stdio.h>
#include "matrix_product.h"
void matrix_product(int m[][3],int DIM)
{
int i,j,k;
int tmp[DIM][DIM];
for(i=0;i<DIM;i++){
for(j=0;j<DIM;j++){
tmp[i][j]=m[i][j];
m[i][j]=0;
}
}
for(i=0;i<DIM;i++){
for(j=0;j<DIM;j++){
for(k=0;k<DIM;k++){
m[i][j]+=tmp[i][k]*tmp[k][j];
}
}
}
}
matrix_product.h
#ifndef MATPROD
#define MATPROD
void matrix_product(int m[][3],int DIM);
#endif // MATPROD
main.c seems to be the only source file added to the project in CodeBlocks. Add the source file matrix_product.c to the project by using Project->Add files and it'll compile that too and link (ld) with the object file it produces.
Just having the file in the same folder does not make CodeBlocks understand that it should include the file in the project.
My files are
// main.c
#include <ClasseAusiliaria.c>
int main(void) {
int result = add(5,6);
printf("%d\n", result);
}
and
// add.c
int add(int a, int b) {
return a + b;
}
Use double quotes #include "ClasseAusiliaria.c" [Don't use angle brackets (< >) ]
And I prefer to save the file with .h extension In the same directory/folder.
TLDR:
Replace #include <ClasseAusiliaria.c> with
#include "ClasseAusiliaria.c"
Change your Main.c like so
#include <stdlib.h>
#include <stdio.h>
#include "ClasseAusiliaria.h"
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
Create ClasseAusiliaria.h like so
extern int addizione(int a, int b);
I then compiled and ran your code, I got an output of
11
You must declare
int add(int a, int b); (note to the semicolon)
in a header file and include the file into both files.
Including it into Main.c will tell compiler how the function should be called.
Including into the second file will allow you to check that declaration is valid (compiler would complain if declaration and implementation were not matched).
Then you must compile both *.c files into one project. Details are compiler-dependent.
make a file classAusiliaria.h and in there provide your method signatures.
Now instead of including the .c file include this .h file.
There are many great contributions here, but let me add mine non the less.
First thing i noticed is, you did not make any promises in the main file that you were going to create a function known as add(). This count have been done like this in the main file:
int add(int a, int b);
before your main function, that way your main function would recognize the add function and try to look for its executable code.
So essentially your files should be
Main.c
int add(int a, int b);
int main(void) {
int result = add(5,6);
printf("%d\n", result);
}
and
// add.c
int add(int a, int b) {
return a + b;
}
You can include the .c files, no problem with it logically, but according to the standard to hide the implementation of the function but to provide the binaries, headers and source files techniques are used, where the headers are used to define the function signatures where as the source files have the implementation. When you sell your project to outside you just ship the headers and binaries(libs and dlls) so that you hide the main logic behind your function implementation.
Here the problem is you have to use "" instead of <> as you are including a file which is located inside the same directory to the file where the inclusion happens. It is common to both .c and .h files
you shouldn't include c-files in other c-files. Instead create a header file where the function is declared that you want to call.
Like so:
file ClasseAusiliaria.h:
int addizione(int a, int b); // this tells the compiler that there is a function defined and the linker will sort the right adress to call out.
In your Main.c file you can then include the newly created header file:
#include <stdlib.h>
#include <stdio.h>
#include <ClasseAusiliaria.h>
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
write main.c like this -
caution : while linking both main.0 and ClasseAusiliaria.o should be
available to linker.
#include <stdlib.h>
#include <stdio.h>
extern int addizione(int a, int b)
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
I am currently working on my first "serious" C project, a 16-bit vm. When I split up the files form one big source file into multiple source files, the linker (whether invoked through clang, gcc, cc, or ld) spits out a the error:
ld: duplicate symbol _registers in register.o and main.o for inferred
architecture x86_64
There is no declaration of registers anywhere in the main file. It is a uint16_t array if that helps. I am on Mac OS 10.7.3 using the built in compilers (not GNU gcc). Any help?
It sounds like you've defined a variable in a header then included that in two different source files.
First you have to understand the distinction between declaring something (declaring that it exists somewhere) and defining it (actually creating it). Let's say you have the following files:
header.h:
void printIt(void); // a declaration.
int xyzzy; // a definition.
main.c:
#include "header.h"
int main (void) {
xyzzy = 42;
printIt();
return 0;
}
other.c:
#include <stdio.h>
#include "header.h"
void printIt (void) { // a definition.
printf ("%d\n", xyzzy);
}
When you compile the C programs, each of the resultant object files will get a variable called xyzzy since you effectively defined it in both by including the header. That means when the linker tries to combine the two objects, it runs into a problem with multiple definitions.
The solution is to declare things in header files and define them in C files, such as with:
header.h:
void printIt(void); // a declaration.
extern int xyzzy; // a declaration.
main.c:
#include "header.h"
int xyzzy; // a definition.
int main (void) {
xyzzy = 42;
printIt();
return 0;
}
other.c:
#include <stdio.h>
#include "header.h"
void printIt (void) { // a definition.
printf ("%d\n", xyzzy);
}
That way, other.c knows that xyzzy exists, but only main.c creates it.
I'm trying to understand how global variables and functions work in C. My program compiles and works fine with gcc, but does not compile with g++. I have the following files:
globals.h:
int i;
void fun();
globals.c:
#include "stdlib.h"
#include "stdio.h"
void fun()
{
printf("global function\n");
}
main.c:
#include "stdlib.h"
#include "stdio.h"
#include "globals.h"
void myfun();
int main()
{
i=1;
myfun();
return 0;
}
And finally, myfun.c:
#include "stdlib.h"
#include "stdio.h"
#include "globals.h"
void myfun()
{
fun();
}
I get the following error when compiling with g++:
/tmp/ccoZxBg9.o:(.bss+0x0): multiple definition of `i'
/tmp/ccz8cPTA.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
Any ideas why? I would prefer to compile with g++.
Every file you include globals.h from will define "int i".
Instead, put "extern int i;" into the header file and then put the actual definition of "int i = 1;" in globals.c.
Putting header guards around globals.h would be sensible too.
Edit: In answer to your question its because a #include works kind of like a cut and paste. It pastes the contents of the included file into the c file that you are calling include from. As you include "globals.h" from main.c and myfun.c you define int i = 1 in both files. This value, being global, gets put into the table of linkable values. If you have the same variable name twice then the linker won't be able to tell which one it needs and you get the error you are seeing. Instead by adding extern on the front in the header file you are telling each file that "int i" is defined somewhere else. Obviously, you need to define it somewhere else (and ONLY in one place) so defining it in globals.c makes perfect sense.
Hope that helps :)
I would add an include guard in your globals file
#ifndef GLOBALS_H
#define GLOBALS_H
int i;
void fun();
#endif
Edit: Change your globals to be like this (using extern as the other answer describes)
globals.h
extern int i;
extern void fun();
globals.c
#include "stdlib.h"
#include "stdio.h"
int i;
void fun()
{
printf("global function\n");
}
I compiled it with
g++ globals.c main.c myfun.c
and it ran ok
Several things wrong here; several other things highly recommended:
globals.h:
#ifndef GLOBALS_H
#define GLOBALS_H
extern int my_global;
#ifdef __cplusplus
extern "C" {
#endif
void fun();
#ifdef __cplusplus
}
#endif
#endif
/* GLOBALS_H */
globals.c:
#include <stdlib.h>
#include <stdio.h>
#include "globals.h"
int my_global;
void fun()
{
printf("global function: %d\n", my_global);
}
main.c:
#include <stdlib.h>
#include <stdio.h>
#include "globals.h"
void myfun();
int main()
{
my_global=1;
myfun();
return 0;
}
void myfun()
{
fun();
}
You should declare "extern int myvar" in your header, and actually allocate "int myvar" in one and only one .c file.
You should include "globals.h" in every file that uses "myvar" - including the file where it's allocated.
Especially if you're planning on mixing C and C++ modules, you should use 'extern "C"' to distinguish non-C++ functions.
System headers should be "#include <some_header.h>"; your own headers should use quotes (#include "myheader.h") instead.
Short variable names like "i" might be OK for a strictly local variable (like a loop index), but you should always use longer, descriptive names whenever you can't avoid using a global variable.
I added a "printf" for my_global.
'Hope that helps!
I had this problem when porting some old C code to C++. The problem was it was a project that was connected to a database, and i wanted to port the database to c++ but not the rest. The database pulled in some C dependencies that couldn't be ported, so i needed the C code that overlapped both the database and the other project to compile in g++ as well as gcc...
The solution to this problem is to define all variables as extern in the .h file. then when you compile in either gcc or g++ it will report symbols missing in the .c files. So edit the .c files in the error messages and insert the declaration into all the .c files that need the variables. Note: you may have to declare it in multiple .c files, which is what threw me and why I was stuck on this problem for ages.
Anyway this solved my problem and the code compiles cleanly under both gcc and g++ now.
I'm trying to compile a simple C program using gcc:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lbryTest.h"
int main(int argc, char *argv[]) {
double x = 0.0;
x = lbryTest(2.0, 5.0);
printf("%f", x);
printf("Placeholder");
return 0;
}
lbryTest() is a function that does some simple math operations and returns a double. It is declared in lbryTest.h, and defined in liblbryTest.a.
When I compile the code using
gcc libraryTest.c -l lbryTest
I get the error:
cannot find -llbryTest.
How can I fix this?
Thanks to John Bollinger's comment, it finds the library. I added -L. to the command. This doesn't however answer why it was unable to find the library in the first place. The files are all in the same directory. How can I make it so the library will be found without explicitly adding the path? Or is that unconventional in C, and you should always explicitly add the path to all libraries linked?