Undefined first referenced symbol in file - c

I get this error and I'm not sure how to fix it. This is a project for information retrieval where i am trying to calculate tf-idf using this type (1+log(freq(t,n)))*log(N/k). freq(t,n) is the frequency of a word, t in file n and N is the number of total files, k number of files that contain the word t.
Undefined first referenced
symbol in file
log /var/tmp//ccx8E8Y1.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
here is my fuction where I get the error (i have #include <math.h> in the start):
void makeTF_IDF(char** words,double** weight,char** str){
int i,j,n,f;
char nameout[1024],line[1024];
double tf,idf[1443],t;
FILE *fin;
for(i=0;i<1443;i++){
n=0;
for(j=0;j<26;j++){
strcpy(nameout,strtok(str[j],"."));
strcat(nameout,"out.txt");
fin=fopen(nameout,"r");
while(1){
if(fgets(line,1024,fin)==NULL) break;
if(strstr(line,words[i])!=NULL){
n++;
break;
}
}
fclose(fin);
}
t=26/n;
idf[i]=log(t);
}
for(i=0;i<1443;i++){
for(j=0;j<26;j++){
f=0;
strcpy(nameout,strtok(str[j],"."));
strcat(nameout,"out.txt");
fin=fopen(nameout,"r");
while(1){
if(fgets(line,1024,fin)==NULL) break;
if(strstr(line,words[i])!=NULL) f++;
}
weight[j][i]=(log(1+f))*idf[i];
fclose(fin);
}
}
}

I suppose you are working on a unix environment (and if you are trying to make an executable out of this file only, you do have a main function).
You should compile with a command like this in order to search for the math library when linking:
gcc <your_filename.c> -lm
You should have an executable named a.out in your current working directory after this command

Related

Error while linking main file with my header file : undefined reference to `myHeaderFunction'

I am trying to make my first header file in C.
There are three files in same directory.
myHeaderFile.h
// It is a good practise to only declare function in header file.
int myHeaderFunction();
myHeaderFile.c
#include "myHeaderFile.h"
int myHeaderFunction()
{
return 1;
}
main.c
#include<stdio.h>
#include"myHeaderFile.h"
int main()
{
printf("main function.\n");
int output;
output = myHeaderFunction();
printf("%d\n",output);
return 0;
}
Cronology:
I created the first file myHeaderFile.h and saved it.
Then I created myHeaderFile.h and saved it.
Then, I created main.h and saved it. (I didn't run any of the file above'
I opened console and wrote the command as written below.
Then, I run main.h and it gave the error as mentioned below.
I open the console in the same directory and type:
gcc -Wall -o combined main.c myHeaderFile.c
It creates a file named combined.exe
And then I run main.c and it gives an error
undefined reference to `myHeaderFunction'
collect2.exe: error: ld returned 1 exit status
There are few answers for the error
undefined reference to `myHeaderFunction' but it involves too many function and files and gcc commands that I didn't understood as a begineer.
So I request not to close this answer and give a solution specific to this problem.

GSL multiple error handler definition error when linking

I'm currently trying to use a library previously written by me (matrix.c) within another self-written library (Quaternion.c) by calling it through a header file using the standard method of using a "matrix.h" file with function prototypes from the "matrix.c" file.
"matrix.c" is functional, but when I attempt to compile "Quaternion.c" in MSYS2 MinGW64, using:
gcc -c matrix.c
gcc -c Quaternion.c
gcc matrix.o Quaternion.o -o Quaternion -lgsl
I'm getting this error:
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: Quaternion.o:Quaternion.c:(.text+0x0): multiple definition of `my_handler'; matrix.o:matrix.c:(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
I defined a custom error handler in the GSL "errono.h", and I'm assuming that's the source of the error:
void my_handler (const char * reason, const char * file, int line, int gsl_errno){
if(gsl_errno == 3 || gsl_errno == 7 || gsl_errno == 8 || gsl_errno == 10){
printf("Fatal memory-based error %d, resetting\n", gsl_errno);
exit(0);
//Reset Chip
}
if(gsl_errno == 1 || gsl_errno == 2 || gsl_errno == 4){
printf("User error %d (%s), ignoring calculation and moving forward\n", gsl_errno, reason);
// Return/ignore calculation
}
else
printf("Unexpected error %d, ignoring and moving forward\n", gsl_errno);
// Return/ignore calculation
}
I can't wrap my head around this error because the gsl library is a single source that I've already edited. If somebody could explain why my compilation method (I'm thinking that's what it is) is resulting in the re-definition of that handler, it would be appreciated.
Move the code quote into one of the .c files.
Then only provide the prototype in the .h file.
void my_handler (const char * reason, const char * file, int line, int gsl_errno);
Otherwise the function is defined once for each .c file which gets compiled and does a #include of that header. In your case probably twice.
A reinclusiong guard would not help in this case, because it still happens once per compiled .c file. But having a guard is still a good idea, I assume you have.

Using the system function to run another .cpp file [duplicate]

This question already has an answer here:
Compiling a source file using system(), 'main referenced from implicit entry/start for main executable [closed]
(1 answer)
Closed 6 years ago.
This program is a'grader' program, where I simply request the user to enter the name of a txt file and a .cpp source file which processes the txt file and gets its info. I then compile the source file along with the txt file, which outputs another text file. This new textile is then compared to the output expected(which I have been given as well.).
The system function allows users to run UNIX commands from a C program. When I am trying to compile the source file the user provides
I am getting an error saying that
"_main", referenced from: implicit entry/start for main executable.
clang: error: linker command failed with exit code 1 (use -v to see invocation)
sh: ./myProg: No such file or directory
The source file that I am compiling provided by my professor has one function which looks like this :
#include <stdio.h>
#include <stdlib.h>
#define MAX_VALUES 3
#define OUTPUT_LINES 5
int notmain(int argc, char **argv)
{
/*
* argv is just the file name
*/
//printf(argv[1]);
int values[MAX_VALUES];
int i, j;
FILE *inputFile;
char name [20]="input.txt"; // I have included this piece of code to see if there is a correct output from the source file provided by the user.
if ( (inputFile = fopen(name, "r") ) == NULL) {
printf("Error opening input file.\n\n");
exit(1);
}
for(i = 0; i < MAX_VALUES; i++)
fscanf(inputFile, "%d", &values[i]);
for(i = 0; i < OUTPUT_LINES; i++){
for (j=0; j < MAX_VALUES; j++)
printf("%d ", values[j]*(i+1) + j);
printf("\n");
}
return 0;
}
The code that I have written can be seen below: This code takes the information from the user and then compiles it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_LINES 5
int main(){
char srcfile[200];
char inpfile[200];
char resultfile[200];
printf("Please enter the name of the source file: \n");
scanf("%s",srcfile);
printf("Please enter the name of the input file: \n");
scanf("%s",inpfile);
printf("Please enter the name of the expected result file: \n");
scanf("%s",resultfile);
char test1 [100]="gcc -o myProg ";
char test2 [100]="./myProg ";
strcat(test2,inpfile);
strcat(test2," > ");
strcat(test2,resultfile);
strcat(test1,srcfile);
printf("%s\n",test1); //these are just tests
printf("%s",test2); //these are just tests
if (system(test1)) {
printf("There is an error compiling the program ");
}
if (system(test2)!= 0) {
printf("There is an error running the executable");
}
return 0;
}
If you are looking for the solution I have posted it in the answers
The file you're trying to compile doesn't have a main function, which is the entry point for C programs. This means that it's actually not possible to build that file alone into an executable.
If the name of the function is supposed to be notmain then you'll have to write another source file that has a main function and calls notmain. This second main would belong to the executable your program is compiling, not to your program. You would have three source files:
Your grader program, which handles compilation.
A sort of wrapper file that effectively does:
int main(int argc, char *argv[]) {
notmain(argc, argv);
}
And finally the program to be graded.
You'll also either need to extern the notmain function or provide a header to share it. Your grader program would then compile the wrapper main and the source file to be graded together.
The question: Can you run two c programs with 2 main functions? The answer: Yes . In order to do this you have to use the terminal to compile the program with the two main functions separately. However if they interact with one another Im afraid I don't have a solution to that Now in this specific case here is how I did it. I went to the terminal and wrote. In this case I run one program which runs another program using the system function
gcc -c main.c (this compiles the main function).
Then after that i wrote gcc -o Myprogram main.o
This will create an executable named Myprogram which you can run by writing
./Myprogram
In this case my main method is compiling another source file so I don't need to compile that program as well in the terminal. When i compiled this program it created an output.txt file in the same directory the executable and the source files are in.

Only first function in header works but the last two don't in c

I made this header for some program functions:
#ifndef STRING_H_INCLUDED
#define STRING_H_INCLUDED
#include <stdio.h>
int s_length(char *test_string){ //returns string length
int i=0;
while(*test_string){
i++;
test_string++;
}
return i;
};
void s_insert(char *string_one){ //inserts string
scanf("%s",string_one);
};
void s_output(char *string_one){ //outputs string
printf("%s",string_one);
};
#endif
and I call the functions in the c file like 2 times each. But the last 2 of them get this: warning: implicit declaration of function ‘s_insert’ and undefined reference to 's_insert'. for both functions.
What does this mean, and what did I do wrong?
It might have to do with the main c file in which I call the functions.
main progam:
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
char *name,*surname;
void menu(){
int choise;
do{
printf("1: incerici dati\n");
printf("2: output dati\n");
printf("3: calcola lungezza\n");
printf("0: ecsi\n");
printf("incerici: ");
scanf("%d", &choise);
printf("------------------\n");
switch(choise){
case 1:
printf("String 1:");
s_insert(name);
printf("String 2:");
s_insert(surname);
printf("------------------\n");
break;
case 2:
s_output(name);
s_output(surname);
printf("------------------\n");
break;
case 3:
printf("string 1: %s lungezza: %d \n",name,s_length(name));
printf("string 2: %s lungezza: %d \n",surname,s_length(surname));
printf("------------------\n");
break;
case 0:
printf("prgram closed!!\n");
break;
default:
printf("Errore: %d schelta invalida\n",choise);
break;
}
}while(choise);
};
int main(int argc, char *argv[]){
name=malloc(sizeof(char)*20);
surname=malloc(sizeof(char)*30);
menu();
return 0;
}
ps fot the people wondering, the printed text is italian because it's a school exercice.
I compiled your code in .c file and compiled it. I was hoping to get error as
string.h : No such file or directory
but,as string.h is also a name of standard C library compiler gave me
[Warning] implicit declaration of function 's_insert' [-Wimplicit-function-declaration]
Hope above explanation gives you a clue.
Most probably:
Your header and source are not in same folder.
OR
Your include path not set to correct location
OR
3.You are having other name to header than string.h
Note:
Copying your header code into string.h created by me works well.
It's very likely that the string.h that got included was not "your" string.h but the C library's string.h. I'm only guessing because you didn't show us how you invoked the compiler.
You should rename your header file.
Also, you shouldn't define functions in a header, only declare them:
int s_length(char *test_string); //returns string length
void s_insert(char *string_one); //inserts string
The implementation should be in another c file (what you have in your header file now). Then you should build the main file and the file implementing your functions, together:
$ gcc -Wall -pedantic -W main.c functions.c
If you are still getting the warning: implicit declaration of function ‘s_insert’ and undefined reference to 's_insert' messages, that means that your header (whatever its name) was not processed by the compiler. If you did not get a fatal error: string.h: No such file or directory message, that means another file with the same name was found (that's why string.h is a bad idea for your own file). To check what files are included, add the -H switch to GCC (or /showIncludes if you are using Microsoft Visual Studio).

Share global variable between .c file

Hi I just wondering how to Share global variable between .c file.
I try to add follow code, but still get error.
test.c file
#include <stdio.h>
int max = 50;
int main()
{
printf("max %d", max); // result max 50
}
pass.h
extern int max;
passed.c
#include <stdio.h>
#include "pass.h"
max;
int main()
{
printf("pass %d \n", max);
return 0;
}
But when I compile passed.c I get follow error
Undefined symbols for architecture x86_64:
"_max", referenced from:
_main in passed-iOMugx.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Can anyone help? Thank you so much.
You can declare the variable in a header file, e.g. let's say in declareGlobal.h-
//declareGlobal.h
extern int max;
Then you should define the variable in one and only file, e.g. let's say, test.c. Remember to include the header file where the variable was declared, e.g. in this case, declareGlobal.c
//test.c
#include "declareGlobal.h"
int max = 50;
You can then use this variable in any file- just remember to include the header file where it's declared (i.e. declareGlobal.c), for example, if you want to use it in passed.c, you can do the following:
//passed.c
#include <stdio.h>
#include "declareGlobal.h"
#include "test.c"
int main()
{
printf("pass %d \n", max);
return 0;
}
The problem is that you have two programs, and data (like variables) can not be shared that simply between programs.
You might want to read about shared memory and other inter-process communication methods.
If on the other hand you only want to have one program, and use a variable defined in another file, you still are doing it wrong. You can only have one main function in a single program, so remove the main function from one of the source files. Also in pass.c the expression max; does nothing and you don't need it.
Then pass both files when compiling, like
$ clang -Wall -g test.c pass.c -o my_program
After the above command, you will (hopefully) have an executable program named my_program.

Resources