I have this C code:
#include <stdio.h>
int main(void)
{
int courses = 1, groups, students = 54, average_pr_group;
/* The variable groups is uninitialized */
average_pr_group = students / groups;
printf("Groups: %d\n", groups);
printf("There are %d students pr. group in %d course(s)\n", average_pr_group, courses);
return 0;
}
Now i compile this using this command from the shell (cmd):
gcc test.c -o test.exe -lm -Wall
It compiles fine, but when I try to run the generated .exe through Windows Explorer I get this error:
In contrast, I can compile & run this piece of code just fine:
# include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
I have MinGW installed at C:\MinGW
This is my user PATH variable:
I can run the .exe just fine with msys, is it just built to withstand those kind of errors?
Variable groups is probably zero, therefore you divide by zero:
average_pr_group = students / groups;
as variable groups is uninitialized it has a undefined or garbage value and that's why the program is crashing...dividing by an uninitialized variable leads to crashing......
Related
#include <stdio.h>
#include <math.h>
int exp_for_level(int n) {
return (int)(100 * pow(n, 2.3));
}
int main(){
int x;
x = exp_for_level(6);
printf("%d", x);
return 0;
}
I receive the following error when I run this code on an online compiler
/tmp/cc28S7ML.o: In function exp_for_level':
main.c:(.text+0x19): undefined reference to `pow'
collect2: error: ld returned 1 exit status
How do I rectify this?
After I couldn't get it to work on the online compiler, I followed advice from some other threads on
The file is stored under a file grades.c on my mac
I've tried entering this
$ gcc - Wall - lm -o grades grade . c
into my terminal and i just get zsh error: command not found
Any ideas on what the issue is here too?
The online compiler I'm using is
https://www.tutorialspoint.com/compile_c_online.php
EDIT: in my post, in main I'd miswritten the function as exp_to_level instead of exp_for_level. Didn't copy paste the entire code as it's too long. I narrowed it down and retyped it to the portion that yields the error.
There are some errors in your code, you have defined a function exp_for_level but you use exp_to_level.
Then your x variable is not defined
If you fix your code like this:
#include <stdio.h>
#include <math.h>
int exp_for_level(int n) {
return (int)(100 * pow(n, 2.3));
}
int main(){
int x = exp_for_level(6);
printf("%d", x);
return 0;
}
and you compile:
gcc -Wall powtest.c -o powtest -lm
it works.
About the error on the online compiler:
The undefined reference error occurs because you are missing -lm linker option.
Edit the online compiler command clicking on Project->Compile Options:
About this problem on your local machine:
After I couldn't get it to work on the online compiler, I followed
advice from some other threads on The file is stored under a file
grades.c on my mac I've tried entering this
$ gcc - Wall - lm -o grades grade . c
into my terminal and i just get zsh error: command not found
you don't have the compiler installed.
You should install clang, Have a look to this question
First of all your function name is wrong in the main take a look here exp_for_level
and in main its exp_to_level change one of them then also add int x in main to solve the issue.
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.
Having a Major issue with trying to do a multi-threading project for school
I'm just trying to run sample code to see how pthreads work
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum;
void *runner(void *param);
int main(int argc, char *argv[]) {
pthread_t tid;
pthread_attr_t attr;
if (argc !=2){
fprintf(stderr, "usage: a.out <interger value>\n");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, "%d must be >= 0\n",atoi(argv[1]));
return -1;
}
pthread_attr_init(&attr);//get default attributes
pthread_create(&tid,&attr,runner,argv[1]);//create the thread
pthread_join(tid,NULL);//wait for the thread to exit
printf("sum = %d\n",sum);
}
void *runner(void *param) {
int i, upper = atoi(param);
sum = 0;
for (i =1; i <= upper; i++) {
sum += i;
}
pthread_exit(0);
}
And no matter what I do I can't get the code to compile. I get the following error:
Running "/home/ubuntu/workspace/primefactor/assn3.c"
/tmp/cc58AE5c.o: In function 'main':
assn3.c:(.text+0xc4): undefined reference to 'pthread_create'
assn3.c:(.text+0xd5): undefined reference to 'pthread_join'
collect2: error: ld returned 1 exit status
Process exited with code: 1
I've tried writing my own makefile with the -pthread flag; didn't work....
I've tried running
sudo apt-get install libpthread-stubs0-dev
to install the right library; didn't work...
I'm at my wits end to try and get pthreads_create() and pthreads_join() to work and they're the main requirement for my school project. I've already gotten the project working with a normal C program (take numbers from the command line, get the prime factors for each arg, store them in an array, then pass that array and display the results. ex: ./prime.c.o {1..100} would be run from BASH and it outs 1:1 2: 2 3: 3 4: 2 2 etc...
so that's what the output is supposed to be and I'm supposed to do that with threading, but I can't do that if I can't even compile sample code to see how threads work.
I really have already spent several hours searching, trying, but no luck getting rid of these undefined reference errors for pthread_create() and pthread_join() . Any help would be greatly appreciated in figuring out why I get the above errors.
Edit:
Thanks to those that tried answering for me. I don't know why I got the down vote; I'm not very active here and I do try to be polite when asking for help. Anyways I finally figured it out.
If I am using the make file it had to look like this:
assn3:
gcc -g -Wall -pthread assn3.c -o assn3
Then from the command line: make assn3
It appears you haven't specified to the linker about thread library. For multithreading applications, the usual option for gcc is follows (assume your program file name thread1.c):
gcc -D_REENTRANT -lpthread thread1.c -o thread1
It's also recommended to use -Wall -O3 -pedantic-errors to be pedantic about compiler warnings etc. So this should do:
gcc -Wall -O3 -pedantic-errors -D_REENTRANT -lpthread thread1.c -o thread1
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.
I'm compiling the below C code with gcc. No errors are thrown during compilation or at runtime. I ran through the code with gdb, and the answer given in sum is correct at the end, yet the printf() does not display anything on the screen. I've tried all sorts of combinations of fprintf(), printf(), and fflush(), but nothing works.
What do I need to change so the program will print the result to stdout?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 9;
int i, sum; i = 1, sum = 0;
while (i < 2 * num) {
sum = sum + i * i;
++i;
}
printf("sum: %d\n", sum);
fflush(stdout);
return 0;
}
The code is correct, and should print sum: 1785 for any conforming implementation.
This is a guess (update: which turns out to be correct), but ...
You've named the source file test.c, and you compile it with:
$ gcc test.c -o test
(or something similar) and execute it with:
$ test
which produces no output.
The problem is that test is a standard Unix command (and also a built-in command in some shells). When you type a command name to the shell, it first looks for built-in commands, then for executables in directories specified in your $PATH environment variable.
To execute a command in the current directory, prepend ./ to the name:
$ ./test
sum: 1785
$
This applies to any command in the current directory. There are so many built-in commands that you can't reasonably avoid colliding with them. Cultivating the habit of running executables in the current directory by typing ./whatever means that name collisions don't matter.
(Don't be tempted to add . to the front of your $PATH; that's dangerous. Think about what could happen if you cd into a directory and type ls, if there happens to be a malicious ls command there.)
There is nothing wrong with your program. It has to work. Try running it with redirection:
./a.out > myout
..and see if you get any output. If not, I'd suspect there is a problem with some kind of standard library mismatch.
Another option to check would be to build using SUN C compiler as opposed to gcc and see if that works. If it does, gcc is the culprit.