TrueStudio - Why does the link static library fail? - linker

I am using TrueStudio for my own stm32 project. I create 2 file foo.h and foo.c includes 2 functions
//foo.h
int add(int a, int b);
int sub(int a, int b);
and the implementation of timeout
//foo.c
#include "foo.h"
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
After that, I used gcc to compile a static library foo.a. I continue to make the main file to implement the library to test.
//main.c
#include <stdio.h>
#include "foo.h"
int main(int argc, const char *argv[])
{
int a = 100, b = 50;
printf("sum is: %d\n", add(a,b));
printf("sub is: %d\n", sub(a,b));
return 0;
}
Next, I link the static foo lib to main.c to make an executable file using command is
gcc main.c foo.a -o main
I ran it and get the result is
sum is: 150
sub is: 50
That's worked fine prove my static lib was built successfully.
I begin to create a project stm32 from stmcubeMX and linker to this foo.a and the error appeared.
undefined reference to 'add'
undefined reference to 'sub'
My full code and setting path and build bellow
//main.c in TrueStudio
#include "main.h"
#include "foo.h"
int main(void)
{
HAL_Init();
SystemClock_Config();
int a = 200, b = 100;
int _sum, _sub;
_sum = add(a, b);
_sub = sub(a, b);
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
}
I am very grateful for any help, thanks!

Rename your foo.a file to libfoo.a, then change the C Linker -> Libraries -> Libraries to just foo with nothing in front or in the back. This should cause the final output to be -lfoo, which in turn causes linker to search for libfoo.a in the library search paths.

Related

Importing a C function

What's wrong with the following import statement? I feel like I'm screwing up something pretty basic here:
// main.c
#include <stdio.h>
#include "1_square.h"
int main(int argc, char *argv[]) {
int a=4;
int a_squared=square(a);
printf("Square of %d is %d\n", a, a_squared);
return 0;
}
// 1_square.h
int square(int num);
// 1_square.c
int square(int num) {
return num*num;
}
$ gcc 0_main.c -o 0_main && ./0_main
/usr/bin/ld: /tmp/cc6qVzAM.o: in function main': 0_main.c:(.text+0x20): undefined reference to square'
collect2: error: ld returned 1 exit status
Or does gcc need a reference to 1_square in order to build it?
You need to add the 1_square.c file to your build command:
gcc -o 0_main 0_main.c 1_square.c && ./0_main
You need the definition of the function as well as its declaration.
From the comments:
Why then does it need 1_square.c in the commandline and then also 1_square.h in the 0_main.c header?
Like John Bollinger points out in the comments, the only thing 1_square.h and 1_square.c have in common is their name, which isn't meaningful to the compiler. There's no inherent relationship between them as far as gcc is concerned.
Let's start by putting everything in one source file:
/** main.c */
#include <stdio.h>
int square( int num );
int main( int argc, char **argv )
{
int a = 4;
int a_squared = square( a );
printf( "Square of %d is %d\n", a, a_squared );
return 0;
}
int square( int num )
{
return num * num;
}
In C, a function must be declared before it is called in the source code; the declaration introduces the function name, its return type, and the number and types of its arguments. This will let the compiler verify that the function call is written correctly during translation and issue a diagnostic if it isn't, rather than waiting until runtime to throw an error. In this particular case, we specify that the square function takes a single int parameter and returns an int value.
This says nothing about the square function itself or how it operates - that's provided by the definition of the square function later on.
A function definition also serves as a declaration; if both the caller and called function are in the same translation unit (source file), then you can put the definition before the call and not have to mess with a separate declaration at all:
/** main.c */
#include <stdio.h>
int square( int num )
{
return num * num;
}
int main( int argc, char **argv )
{
int a = 4;
int a_squared = square( a );
printf( "Square of %d is %d\n", a, a_squared );
return 0;
}
This is actually preferable as you don't have to update the function signature in two different places. It means your code reads "backwards", but honestly it's a better way to do it.
However, if you separate your function out into a separate source file, then you need to have a separate declaration:
/** main.c */
#include <stdio.h>
int square( int num );
int main( int argc, char **argv )
{
int a = 4;
int a_squared = square( a );
printf( "Square of %d is %d\n", a, a_squared );
return 0;
}
/** square.c */
int square( int num )
{
return num * num;
}
When it's processing main.c, the compiler doesn't know anything about the definition of the square function in square.c - it doesn't even know the file exists. It doesn't matter if main.c is compiled before square.c or vice-versa; the compiler operates on one file at a time. The only thing the compiler knows about the square function is that declaration in main.c.
Having to manually add a declaration for every function defined in the separate .c file is a pain, though - you wouldn't want to write a separate declaration for printf, scanf, fopen, etc. So BY CONVENTION we create a separate .h file with the same name as the .c file to store the declarations:
/** main.c */
#include <stdio.h>
#include "square.h"
int main( int argc, char **argv )
{
int a = 4;
int a_squared = square( a );
printf( "Square of %d is %d\n", a, a_squared );
return 0;
}
/** square.h */
int square( int num );
/** square.c */
int square( int num )
{
return num * num;
}
By convention, we also add include guards to the .h file - this keeps the contents of the file from being processed more than once per translation unit, which can happen if you #include "square.h" and include another header which also includes square.h.
/** square.h */
#ifndef SQUARE_H // the contents of this file will only be
#define SQUARE_H // processed if this symbol hasn't been defined
int square( int num );
#endif
Also by convention, we include the .h file in the .c file to make sure our declarations line up with our definitions - if they don't, the compiler will complain:
/** square.c */
#include "square.h"
int square( int num )
{
return num*num;
}
After both main.c and square.c have been compiled, their object code will be linked into a single executable:
main.c ------+-----> compiler ---> main.o ----+--> linker ---> main
| |
square.h ----+ |
| |
square.c ----+-----> compiler ---> square.o --+
We must compile both C files and link their object code together to have a working program. No doubt your IDE makes this easy - you just add source files to the project and it builds them correctly. gcc lets you do it all in one command, but you must list all the .c files in the project.
If you're running from the command line, you can use the make utility to simplify things. You'll need to create a Makefile that looks something like this:
CC=gcc
CFLAGS=-std=c11 -pedantic -Wall -Werror
main: main.o square.o
all: main
clean:
rm -rf main *.o
All you need to do then is type make at the command line and it will build your project, using built-in rules for compiling main.c and square.c.

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;

How do I include a header from a separate directory in addition to including functions from a file from a different directory?

I have 3 directories, src, lib, and include. In include I have header file header3.h. Its code is as follows:
// header3.h
extern void change(int *a);
In lib I have file change4.c, which contains:
// change4.c
#include <stdlib.h>
#include "header3.h"
void change(int *a){
int y=100;
a=y;
}
In src I have file manipulate5.c, which contains:
// manipulate5.c
#include <stdio.h>
#include "header3.h"
int main(void){
int x=10;
printf("x is %d\n", x );
change(&x);
printf("x is now %d\n", x );
}
When I attempt to compile manipulate5.c with following command:
gcc -I ../include manipulate5.c`
when in directory src, I get the following error:
In function main:
manipulate5.c:(.text+0x2b): undefined reference to change
So how do I get manipulate5.c to properly work?

Functions from header file not working without including .c too

I try to make program in C and I cant use functions from .h without including .c file too. If I include .c after including .h it works. I get "undefined reference to ..." error on every function defined in .h.
main.c:
#include "mp.h"
//#include "mp.c"
int main()
{
int n;
printf("Unesite broj clanova niza: ");
scanf("%d",&n);
int *a=(int *)malloc(n*sizeof(int));
if (a==NULL) exit(0);
unos(a,n);
sortiranje(a,n,rastuci);
stampanje(a,n);
sortiranje(a,n,opadajuci);
stampanje(a,n);
return 0;
}
mp.h:
#ifndef MP_H_INCLUDED
#define MP_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
enum tip_sort {opadajuci,rastuci};
void unos(int *, int);
void sortiranje(int *, int, enum tip_sort);
void stampanje(int *, int);
#endif // MP_H_INCLUDED
mp.c:
#include "mp.h"
void unos(int *a, int n){
...
}
void sortiranje(int *a, int n, enum tip_sort t){
...
}
void stampanje(int *a, int n){
...
}
What you're seeing is a linker error. I guess, you're trying to compile main.c all alone.
You compilation statement should look like
gcc main.c mp.c -o output
and yes, do not #include .c (source) files. Source files are meant to be compiled and linked together to form the binary.
Note: Also, please do not cast the return value of malloc().

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