Functions and variables scope in C - c

Why we don't use extern when using function from one .c file in another .c file , but we must do extern for variables case? Is it related to linker?

Functions are extern qualified by default (unless you change it to internal with static). For example,
int func(void) {
}
extern int func2(void) {
}
Both func and func2 are external. The extern keyword is optional for external functions.

Actually, function names act just like variable names, but function prototypes are extern by default.
From cpprerefence:
If a function declaration appears outside of any function, the identifier it introduces has file scope and external linkage, unless static is used or an earlier static declaration is visible.

you can create a .hfile,declare functions you want to use in the other .c files and #include the .hfile in the other .c files.

Demo program,
one.c
#include "one.h"
void func1() //defination
{
//code
}
one.h
void func1(); //declaration
main.c
#include <stdio.h>
#include "one.h"
int main()
{
func1();
}
Then compile program in Gcc Linux : gcc main.c one.c

Yes, Let consider you have one .c file as process.c and you declared it in process.h . Now if you want to use the function from process.c to suppose tools.c then simply #include "process.h" in tools.c and use ther function. The process.h and process.c file should be in your project.
process.c file
#include<stdio.h>
#include<conio.h>
#include "process.h"
unsigned int function_addition(unsigned int a, unsigned int b)
{
unsigned int c = 0;
c = a + b;
return c;
}
process.h:
<bla bla bla >
unsigned int function_addition(unsigned int a, unsigned int b);
<bla bla bla >
tools.c file:
#include<stdio.h>
#include<conio.h>
#include "process.h"
my_tools()
{
unsigned int X = 1, Y = 9, C = 0;
C = function_addition(X,Y);
}
All these files are in one project.

Related

Is there any wrong about tha static variable?

I have a problem about a program. I bet that it has to do with the fact that I use static. Here is my t.h
static int cnt;
void f();
my main.c
#include <stdio.h>
#include "t.h"
void main()
{
cnt=0;
printf("before f : cnt=%d\n",cnt);
f();
printf("after f : cnt=%d\n",cnt);
}
and finally my f.c
#include "t.h"
void f()
{
cnt++;
}
The printf prints cnt=0 both times. How is this possible when I do cnt++? Any ideas?
Thanks in advance
In C, static means "Local to the module"
Take note, that the #include statements just pastes the header file in the including file.
therefore, you are creating two distinct symbols (happens to have the same logical name) in different modules.
f.c cnt is a different cnt then main.c
Note:
static in C has different meaning then its C++ counterpart.
and because C++ is C Compatible, static outside a class have the same meaning as in C
Edit:
In your case, you don't want a static you want a variable, but i guess you had problem with the Linker telling you about "ambiguous symbols".
I would suggest to declare an extern in the header file, and declare the actual variable in a module.
t.h
extern int cnt; // declaration of the variable cnt
main.cpp
#include
#include "t.h"
void main()
{
cnt=0;
printf("before f : cnt=%d\n",cnt);
f();
printf("after f : cnt=%d\n",cnt);
}
t.cpp
#include "t.h"
int cnt = 0; // actual definition of cnt
void f()
{
cnt++;
}
Data should not be defined in the header files.
In your example you will create a separate copy of that static variable in every compilation module which includes this .h file.
Don't define cnt in your header file. Instead, define it in f.c:
#include "t.h"
int cnt = 0;
void f(){
cnt++;
}
Then in main.c, add the following before the beginning of your main function:
extern int cnt;

multiple definition in linking

I'm a beginner into Linking, lets say I have two .c files
file1.c is
#include <stdio.h>
#include "file2.c"
int main(int argc, char *argv[])
{
int a = function2();
printf("%d",a);
return 0;
}
and file2.c is
int function2()
{
return 2018;
}
when I compiled, there is a linker error which is multiple definition of function2, but I only define function once in file2.c?
You should create a header file, "file2.h", with:
int function2(void);
and a file "file2.c" with the function: "file2.h" with:
#include "file2.h"
int function2(void)
{
return 2018;
...
}
Then in your main you have to include the header with:
#include "file2.h"
Keep care that all those files should be in the same folder to avoid any link problem
Try something like this:
#include <stdio.h>
#include "file2.h"
int main(int argc, char *argv[])
{
int a = function2();
printf("%d",a);
return 0;
}
file2.h:
extern int function2(void);
and file2.c is
#include "file2.h"
int function2(void)
{
return 2018;
}
And then link it together.
The statement #include "file2.c" effectively incorporates the contents of file2.c into file1.c. Then file1.c is compiled as if it contains:
int function2()
{
return 2018;
}
Those lines define function2; they tell the compiler “Here is function2, create code for it.” Because those lines effectively appear in both file1.c and file2.c, your program has two copies of function2.
Instead, you should create file2.h that contains:
int function2();
That line tells the compiler “There exists a function called function2, but its definition is somewhere else.”
Then, in file1.c, use #include "file2.h" instead of #include "file2.c". This will tell the compiler, while file1.c is being compiled, what it needs to know to compile a call to function2. The compiler will have the declaration it needs, but it will not have the definition, which is not needed in file1.c.
Also, in file2.c, insert #include "file2.h". Then file2.c will contain both a declaration of function2 (from file2.h) and a definition of function2 (from the actual lines in file2.c). The purpose of this is so the compiler can see both the declaration and the definition while it is compiling file2.c, so it can warn you if there is a typographical error that makes them incompatible.
Additionally, in C, you should use int function2(void) rather than int function2(). For historic reasons, the latter leaves the parameters unspecified. Using (void) tells the compiler there are no parameters.

How can I call to function that exists in other file?

Given 2 files, for examples:
file1.c :
int main(){
f();
return 0;
}
file2.c:
void f(){
return;
}
Why I can't call f from file1.c like that?
Because first you need to tell the compiler (declare) that it exists somewhere:
void f(); //function declaration
int main()
{
f();
return 0;
}
Usually, though, it is better to put such declarations in a separate header file (e.g. file2.h) so that later you could include this file (e.g. #include "file2.h") instead of duplicating such declaration in every other file where you need this function.
The problem is that file1.c does not "know" that the function f exists. You need to use a prototype. The standard way is to put prototypes in header files and definitions in .c files.
It could look like this:
file1.c:
#include "file2.h"
int main(){
f();
return 0;
}
file2.h:
#ifndef FILE2_H
#define FILE2_H
void f();
#endif
file2.c:
#include "file2.h"
void f(){
return;
}

How to define variables in a header file, C

I want to declare and define (with a default value) a variable in a .h file.
When I do that I get
/tmp/cc19EVVe.o:(.data+0x0): multiple definition of `car_name'
/tmp/cc3twlar.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
How do I achieve my goal? Namely, to declare and define with default values a variable in a .h file and use that variable in multiple .c files?
Here is the A.h file
char * car_name = "Volkswagen";
void execute();
Here are the first file that uses the variable car_name defined in A.h: (The file is called execute.c)
#include "A.h"
#include <stdio.h>
#include <string.h>
void execute(){
int len = sizeof(car_name) + 2;
char car_name_with_new_line[len];
strncat(car_name_with_new_line, car_name, sizeof(car_name));
strncat(car_name_with_new_line, "\n", 1);
printf(car_name_with_new_line);
}
That's the other .c file: (It's called main.c)
#include "A.h"
int main(int argc, char ** argv){
execute();
return 0;
}
The answer is simple: Define your variables in exactly one compilation unit (.c file). Declare them in the header file associated with that .c file.
foo.h
extern char *g_name; // Declare that g_name exists
foo.c
#include "foo.h"
char *g_name; // Define g_name in one place
static char *m_private; // Private to foo.c, not "exported" via foo.h
main.c
#include "foo.h"
void somefunc(void)
{
// use g_name
}
1) define the variable in a single file, do not add a static modifier
2) place an extern statement for that variable in the header file.
then only one instance of the variable exists anyone that includes the header file can access the variable.
Note: it is poor programming practice to have global variables.
Good programming practice is to write accessor functions and hide the variable within a file. similar to the following:
static int myVariable = 0;
void setMyVariable( int myVariableParm )
{
myVariable = myVariableParm;
}
int getMyVariable( void )
{
return myVariable;
}

How to invoke function from external .c file in C?

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

Resources