Weird error by compiling pthreads program

I wrote the following pthreads program:-
It is giving un-understandable errors which I pasted at the bottom of program.

#include<stdio.h>
#include<pthread.h>
#define NUM_THREADS 4

void *hello (void *arg)
{
printf("Hello Thread\n");
}

main()
{
pthread_t tid[NUM_THREADS];
for(int i=0; i<NUM_THREADS; i++)
pthread_create(&tid[i], NULL, hello, NULL);

for(int i=0;i<NUM_THREADS; i++)
pthread_join(tid[i], NULL);

}

----------------------------------------------------------------------
Errors:-
--------
In function âmainâ:
MultipleThreads.c:13: error: âforâ loop initial declarations are only allowed in C99 mode
MultipleThreads.c:13: note: use option -std=c99 or -std=gnu99 to compile your code
MultipleThreads.c:16: error: redefinition of âiâ
MultipleThreads.c:13: note: previous definition of âiâ was here
MultipleThreads.c:16: error: âforâ loop initial declarations are only allowed in C99 mode

for(int i=0; i<NUM_THREADS; i++)

In c, you cannot declare the i inside the for statement.

try like these

1
2
3
4
5
6
7
8
9
10
11
12
main()
{
int i;
pthread_t tid[NUM_THREADS];
for( i=0; i<NUM_THREADS; i++)
pthread_create(&tid[i], NULL, hello, NULL);

for(i=0;i<NUM_THREADS; i++)
pthread_join(tid[i], NULL);

}


Hope it helps
Thanks for your reply.

I made the changes as below:
However, I am still getting 2 minor error which are not going away. I have pasted them at the bottom the the program. If someone can help me , I will appreciate it.


#include<stdio.h>
#include<pthread.h>
#define NUM_THREADS 4

void *hello (void *arg)
{
printf("Hello Thread\n");
}

main()
{
pthread_t tid[NUM_THREADS];
int i;
for(i=0; i<NUM_THREADS; i++)
pthread_create(&tid[i], NULL, hello, NULL);

int j;
for(j=0;j<NUM_THREADS;j++)
pthread_join(tid[j],NULL);
}

-------------------------
Errors:--
------------------------

./helloThread.c: line 5: syntax error near unexpected token `('
./helloThread.c: line 5: `void *hello (void *arg)'
Last edited on
I took your code, compiled, and ran it without issue... I don't see where the problem could be.
Sounds like you forgot to compile the program.
Sounds like you compiled it with a C++ compiler TBH.
These are the error messages you'd get if you tried to run the source code as a bash script.
Oh, that makes sense.
Topic archived. No new replies allowed.