Currently having issues compiling programs that contain multiple files, and working on files outside of main. I suspect it has something to do with the compiler, something to do with the -c command or perhaps something I messed up during installation. Any help wrapping my head around this would be a huge help, I have been asking fellow classmates and checking online but it seems the solution must be a very simple one.
[Running] cd "/Users/shawn/Desktop/c-course/M03/calc/src/" && gcc tempCodeRunnerFile.c -o tempCodeRunnerFile && "/Users/shawn/Desktop/c-course/M03/calc/src/"tempCodeRunnerFile
Undefined symbols for architecture arm64:
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[Done] exited with code=1 in 0.254 seconds`your text
This is the source.c file, the one I was meant to alter.
#include "source.h"
#include <math.h>
#include <stdio.h>
void simple_math(void){
float num1;
float num2;
float result;
char operator;
char space = ' ';
scanf("%f", &num1);
scanf("%c", &space);
scanf("%f", &num2);
scanf("%c", &space);
scanf("%c", &operator); //taking user input
switch(operator) {
case '+':
result = num1 + num2;
printf("%.1f", result);
break;
case '-':
result = num1 - num2;
printf("%.1f", result);
case '*':
result = num1 * num2;
printf("%.1f", result);
case '/':
result = num1 / num2;
printf("%.1f", result);
default:
printf("ERR");
}
printf("%.1f", result);
}
The source.h file just contains
void simple_math(void);
The main file contains the following, with the #include tag including the other files.
#include "source.h"
#include <stdio.h>
int main()
{
printf("\n--- Testing calculator ---\n");
simple_math();
return 0;
}
All the files need to be linked and compiled:
gcc file1.c file2.c -o myprogram
And then run the executable:
./myprogram
You may refer to this answer:
How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"
Related
Consider the following code:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("main\n");
int a;
scanf("%d", &a);
printf("a = %d\n", a);
return 0;
}
int main1() {
printf("main1\n");
int a;
scanf("%d", &a);
printf("a = %d\n", a);
exit(0);
return 0;
}
int main2() {
printf("main2\n");
int a = getchar() - '0';
int b = getchar() - '0';
int c = getchar() - '0';
printf("a = %d\n", 100 * a + 10 * b + c);
exit(0);
return 0;
}
Assuming that the code resides in a file called test.c, the following works fine (it prints "a = 123"):
gcc -o test test.c
echo 123 | ./test
If, however, I run the program with a custom entry point, I get the dreaded Segmentation fault:
gcc -o test test.c -e"main1"
echo 123 | ./test
But if I replace the scanf with three getchars, the program runs fine again despite being run with a custom entry point:
gcc -o test test.c -e"main2"
echo 123 | ./test
To make things even more interesting, these problems occur with gcc 7.4.0 but not with gcc 4.8.4.
Any ideas?
The -e command line flag redefines the actual entry point of your program, not the “user” entry point. By default, using GCC with the GNU C standard library (glibc) this entry point is called _start, and it performs further setup before invoking the user-provided main function.
If you want to replace this entry point and continue using glibc you’ll need to perform further setup yourself. But alternatively you can use the following method to replace the main entry point, which is much simpler:
gcc -c test.c
objcopy --redefine-sym main1=main test.o
gcc -o test test.o
Note, this will only work if you don’t define main in your code, otherwise you’ll get a “multiple definition of `main'” error from the linker.
I am attempting to create a makefile for a simple program which relies on a simple file and a function stored in a c file. Here are the files:
function.c:
int random_fun(int n, int m)
{ int g;
n = n+m;
m=n/3;
g=n*m;
return g;
}
main.c:
#include <stdio.h>
#include "function.c"
int main()
{
int a, b;
printf("Enter numbers a, and b: ");
scanf("%d %d", &a, &b);
printf("Here is ur answer: %d", random_fun(a, b));
return 0;
}
And here is my makefile:
OBJS = main.o function.o
program: $(OBJS)
$(CC) -o $# $?
clean:
rm $(OBJS) program
Whenever I try type make, I get the following error:
duplicate symbol _random_fun in:
main.o
function.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)
make: *** [program] Error 1"
Not sure what I am doing wrong. I can compile each code separately and main works. I was getting the same error for another project I was working on, so I tried with a very simple case involving only these 2 C files, and I get the same issues. I am fairly new to makefiles and what not, so bear with me if I am making a stupid mistake.
You should read about difference between definition and declaration in C.
As you're including function.c into your main.c, your function random_func is defined two times. Linker can't decide for you which one to use, so it errors out.
For your use case you should declare random_func in main.c or additional header file.
This is what happens with your files after preprocessing:
// function.c
int random_fun(int n, int m)
{ int g;
n = n+m;
m=n/3;
g=n*m;
return g;
}
-
// main.c
// contents of stdio.h goes first. I omit it for brevity
int random_fun(int n, int m)
{ int g;
n = n+m;
m=n/3;
g=n*m;
return g;
}
int main()
{
int a, b;
printf("Enter numbers a, and b: ");
scanf("%d %d", &a, &b);
printf("Here is ur answer: %d", random_fun(a, b));
return 0;
}
It means that now you have the same function in two separate files. When you compile both of them the linker sees two valid functions random_fun, it simply does not know which one to use.
There two ways to solve this problem.
Using header
In this case, you would need to create another file, e.g. function.h:
// random.h
int random_fun(int n, int m);
Then, in main.cyou include the header instead of .c:
#include <stdio.h>
#include "function.h" // <-- .h, not .c
int main()
{
int a, b;
printf("Enter numbers a, and b: ");
scanf("%d %d", &a, &b);
printf("Here is ur answer: %d", random_fun(a, b));
return 0;
}
This way you will have only one random_fun function across two files, the linker would not be confused.
Using extern keyword
In your main.c you can define the random_fun function as external. It basically says to a compiler that the function exists somewhere and it will be resolved later by a linker.
#include <stdio.h>
extern int random_fun(int n, int m);
int main()
{
int a, b;
printf("Enter numbers a, and b: ");
scanf("%d %d", &a, &b);
printf("Here is ur answer: %d", random_fun(a, b));
return 0;
}
Again, in this case, you will have just one random_fun function across two files and the linker would not be confused.
As a rule of thumb, I would say you never include .c files unless you absolutely need to. (I can hardly imagine when it may be needed.)
This question already has answers here:
Undefined reference to sqrt (or other mathematical functions)
(5 answers)
Closed 5 years ago.
So I'm trying to make a program that calculates the quadratic formula, but when I try to compile the code, I get the following:"undefined reference to sqrt"
But I tried defining sqrt via math.h and 2 other times in the code.
I have attached my code
Any help would be greatly appreciated
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double sqrt(double);
int main (void) {
double sqrt(double);
int a,b,c;
double discriminant,squarerootofdis,root1, root2;
printf("Please enter the coefficient of x^2:");
scanf("%d",&a);
printf("Please enter the coefficient of x:");
scanf("%d",&b);
printf("Please enter the integer value of the ploynomial:");
scanf("%d",&c);
if (a==0 && b==0)
{printf("This case is extremely degenerate");}
else if (a==0 && b!=0)
{root1=-c/b;
printf("Degenerate one real root: %lf\n",root1);}
else{
discriminant = ((b*b)-(4*a*c));
squarerootofdis = sqrt(discriminant);
root1 = (squarerootofdis-b)/(2*a);
root2 = (-squarerootofdis-b)/(2*a);
if (discriminant>0)
printf("Two real roots: %lf\n %lf\n", root1, root2);
else if (discriminant == 0)
printf("Degenerate one real root: %lf\n",root1);
else if (discriminant<0)
printf("Two complex roots: %lf\n %lf\n", root1, root2);
}
}
To use the sqrt function (or any function defined in math.h), you'll have to link the m library:
~$ gcc -lm yourcode.c -o program
Did you compile with -lm linked?
Header file will provide the decalration to the sqrt() function. To have the definition, you need to link with the math library consisting of the function definition.
Example:
gcc test.c -o output -lm
Please use the below command
gcc test.c -lmath
I just got my Netbeans tools configured,and (finally) it worked :) (I checked with Hello World). We were shifting so I have had like a 3 month gap so I though I'd make a calculator rather than some other program like a palindrome checker and bleh bleh bleh.
So here's the code :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void addition(int,int);
void subtraction(int,int);
void mutiplication(int,int);
void division(int,int);
int main() {
int x,y,choice,redo = 1;
while(redo)
{
printf("\nWelcome to the CalC :D\nPlease make a choice\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n>");
scanf("%d",&choice);
switch(choice);
{
case '1' :
{
printf("Enter the first number\n>");
scanf("%d",&x);
printf("\nThe second number?\n>");
scanf("%d",&y);
addition(x,y);
}
case '2' :
{
printf("Enter the first number\n>");
scanf("%d",&x);
printf("\nThe number to be subtracted from %d is?\n>",x);
scanf("%d",&y);
subtraction(x,y);
}
case '3' :
{
printf("Enter the first number\n>");
scanf("%d",&x);
printf("\nThe number to be multiplied with %d is?\n>",x);
scanf("%d",&y);
multiplication(x,y);
}
case '4' :
{
printf("Enter the first number\n>");
scanf("%d",&x);
printf("\nThe number to be divided by %d is?\n>",x);
scanf("%d",&y);
division(x,y);
}
}
printf("\nWould you like to make another calculation?\n1.Yes '_' \n2.No! :p\n>");
scanf("%d",&redo);
}
return (EXIT_SUCCESS);
}
void addition(int x,int y)
{
int sum;
sum = x + y;
printf("\nThe sum of %d and %d is %d\n(Press enter to display the menu)",x,y,sum);
getch();
}
void subtraction(int x,int y)
{
int difference;
ce;
difference = x - y;
printf("The difference between %d and %d is %d\n(Press enter to display the menu)",x,y,difference);
getch();
}
void multiplication(int x,int y)
{
int product;
product = x * y;
printf("The product of %d and %d is %d\n(Press enter to display the menu)",x,y,product);
getch();
}
void division(int x,int y)
{
float quotent;
quotent = (float)x/(float)y;
printf("The quotient of %d and %d is %.2f\n(Press enter to display the menu)",x,y,quotent);
getch();
}
And this is the error I get :
"/C/MinGW/bin/make.exe" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
make[1]: Entering directory 'C:/Users/CaptFuzzyboots/Documents/NetBeansProjects/CalC'
"c:/MinGW/bin/make.exe" -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/calc.exe
make[2]: Entering directory 'C:/Users/CaptFuzzyboots/Documents/NetBeansProjects/CalC'
mkdir -p build/Debug/MinGW-Windows
rm -f build/Debug/MinGW-Windows/main.o.d
gcc -c -g -MMD -MP -MF build/Debug/MinGW-Windows/main.o.d -o build/Debug/MinGW-Windows/main.o main.c
main.c: In function 'main':
main.c:26:5: error: case label not within a switch statement
main.c:34:9: error: case label not within a switch statement
main.c:42:9: error: case label not within a switch statement
main.c:52:9: error: case label not within a switch statement
main.c: In function 'subtraction':
main.c:78:5: error: 'ce' undeclared (first use in this function)
main.c:78:5: note: each undeclared identifier is reported only once for each function it appears in
main.c: At top level:
main.c:83:6: warning: conflicting types for 'multiplication' [enabled by default]
main.c:48:13: note: previous implicit declaration of 'multiplication' was here
nbproject/Makefile-Debug.mk:66: recipe for target 'build/Debug/MinGW-Windows/main.o' failed
make[2]: *** [build/Debug/MinGW-Windows/main.o] Error 1
make[2]: Leaving directory 'C:/Users/CaptFuzzyboots/Documents/NetBeansProjects/CalC'
nbproject/Makefile-Debug.mk:59: recipe for target '.build-conf' failed
make[1]: *** [.build-conf] Error 2
make[1]: Leaving directory 'C:/Users/CaptFuzzyboots/Documents/NetBeansProjects/CalC'
nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
make: *** [.build-impl] Error 2
BUILD FAILED (exit value 2, total time: 661ms)
I'm used to code::blocks so I don't really know what's the problem here :\
please help me out,I clearly defined the switch labels as '1','2','3','4'!
Thanks guys :)
You have an extra semicolon after switch(choice). Your code has
switch(choice);
and it should be
switch(choice)
A few other problems:
1) You misspelled multiplication when you defined the function at the top.
2) There's a stray ce; in your subtraction function.
3) You don't have any break statements in your case statements (it looks like you don't want the cases to fall through, so you probably need them)
4) choice is an int, but you're casing on chars. Since you're reading ints with scanf, you probably want to have 1,2,3,4 instead of '1','2','3','4'.
Your main issue is the extra semi-colon after switch (choice). Remove that semi-colon, and be sure to have a break after each case as well.
You also have choice declared as an integer, but your case labels are switching on a char; it would be advisable to get rid of the single quotes around each case.
do case '1' instead of case 1
write multiplication and not mutiplication
remove the "ce" from the subtraction function
remove semicolon after switch(choice)
have a 'break' in each case
at the begining, correct spelling of multiplication
remove "ce;" inside the function subtraction.
Change cases '1', '2', etc to 1, 2...
Please note that, running a normal C code from Netbeans IDE should produce the same result if you run it in Eclipse or some other IDE. Your error is noway related to Netbeans.
I am trying to write a program to approximate pi. It basically takes random points between 0.00 and 1.00 and compares them to the bound of a circle, and the ratio of points inside the circle to total points should approach pi (A very quick explanation, the specification goes in depth much more).
However, I am getting the following error when compiling with gcc:
Undefined first referenced
symbol in file
pow /var/tmp//cc6gSbfE.o
ld: fatal: symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
What is happening with this? I've never seen this error before, and I don't know why it's coming up. Here is my code (though I haven't fully tested it since I can't get past the error):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
float x, y;
float coordSquared;
float coordRoot;
float ratio;
int n;
int count;
int i;
printf("Enter number of points: ");
scanf("%d", &n);
srand(time(0));
for (i = 0; i < n; i++) {
x = rand();
y = rand();
coordSquared = pow(x, 2) + pow(y, 2);
coordRoot = pow(coordSquared, 0.5);
if ((x < coordRoot) && (y < coordRoot)) {
count++;
}
}
ratio = count / n;
ratio = ratio * 4;
printf("Pi is approximately %f", ratio);
return 0;
}
use -lm during compilation(or linking) to include math library.
Like this: gcc yourFile.c -o yourfile -lm
need to Link with -lm.
gcc test.c -o test -lm
The error is produced by the linker, ld. It is telling you that the symbol pow cannot be found (is undefined in all the object files handled by the linker). The solution is to include the library which includes the implementation of the pow() function, libm (m for math). [1] Add the -lm switch to your compiler command line invocation (after all the source file specifications) to do so, e.g.
gcc -o a.out source.c -lm
[1] Alternatively, you could have your own implementation of pow() in a separate translation unit or a library, but you would still have to tell the compiler/linker where to find it.