I'm having trouble compiling my code, which uses a mutex (so uses pthread locks and conditions). I've tried including the header file, compiling with -pthread or -lpthread, but I'm still getting an error. Help would be much appreciated.
This is the error output:
implicit declaration of function ‘Pthread_mutex_lock’ [-Wimplicit-function-declaration]
Pthread_mutex_lock(&lock); //locked
^
/tmp/cchVS47i.o: In function getMessage1':
hw3.c:(.text+0x22): undefined reference toPthread_mutex_lock'
hw3.c:(.text+0x50): undefined reference to Pthread_mutex_lock'
/tmp/cchVS47i.o: In functiongetMessage2':
hw3.c:(.text+0x13e): undefined reference to `Pthread_mutex_lock'
collect2: error: ld returned 1 exit status
And here's relevant sections of my code (edited for clarity):
#define _GNU_SOURCE
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
char message[1001];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
void *getMessage1()
{
Pthread_mutex_lock(&lock); //locked
....
}
int main(void)
{
pthread_t id1;
pthread_t id2;
pthread_create((&id1), NULL, getMessage1, NULL);
pthread_create((&id2), NULL, getMessage2, NULL);
...
return 0;
}
It's the capital P you have in
Pthread_mutex_lock(&lock); //locked
in the beginning of the function getmessage1().
Your compiler is complaining that it has not seen a declaration for that function in the compiling phase. Also it is complaining about that in the linking phase. You are including all the right libraries because it is not complaining about any of the other functions that are correctly typed.
The correct name of the function is pthread_mutex_lock().
In original k&r C it is possible to use functions without declarations, although compilers warn about them. In more modern versions of C (99) this has been deprecated.
Related
This question already has answers here:
Undefined reference to pthread_create in Linux
(16 answers)
Closed 1 year ago.
So I am writing a program in C that creates 4 threads that produce/consume from buffers. I initialized all the threads in my main function but I am getting the following error. Does anyone know why? I ran it on my local zsh shell on macOS and it works fine. But when I try running it on my school's server, I think it's linux with bash, it gives me the errors.
flip1 ~/CS344/assignment4 1022$ gcc -std=gnu99 -o line-processor line_processor2.c
/tmp/ccYF7Kqe.o: In function `main':
line_processor2.c:(.text+0x7b5): undefined reference to `pthread_create'
line_processor2.c:(.text+0x7d9): undefined reference to `pthread_create'
line_processor2.c:(.text+0x7fd): undefined reference to `pthread_create'
line_processor2.c:(.text+0x821): undefined reference to `pthread_create'
line_processor2.c:(.text+0x832): undefined reference to `pthread_join'
line_processor2.c:(.text+0x843): undefined reference to `pthread_join'
line_processor2.c:(.text+0x854): undefined reference to `pthread_join'
line_processor2.c:(.text+0x865): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
Below is my main function
int main()
{
pthread_t inputThread, lineSeparatorThread, plusSignThread, outputThread;
pthread_attr_t attr;
// Set up Sentinal Values at the begining of each buffer to indicate whether or not
// the buffer line has been read or not
for (int i = 0; i < BUFSIZE; i++)
{
buffer1[i][0] = -1;
buffer2[i][0] = -1;
buffer3[i][0] = -1;
}
// Initialize a pthread attribute structure to set up joinable threads
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
// Initialize mutex and condition variables
pthread_mutex_init(&mutex1, NULL);
pthread_mutex_init(&mutex2, NULL);
pthread_mutex_init(&mutex3, NULL);
pthread_cond_init(&readyBuffer1, NULL);
pthread_cond_init(&readyBuffer2, NULL);
pthread_cond_init(&readyBuffer3, NULL);
// Set up the thread in reverse order so that the readers/consumers will pend
// waiting for the writers/consumers to start up
pthread_create(&outputThread, &attr, output_thread, NULL);
usleep(100); // Force the program to allow output thread to actually come up and pend on readyBuffer 3 first
pthread_create(&plusSignThread, &attr, plus_sign_thread, NULL);
usleep(100); // Force the program to allow plus_sign_thread thread to actually come up first
pthread_create(&lineSeparatorThread, &attr, line_separator_thread, NULL);
usleep(100); // Force the program to allow line_separator_thread thread to actually come up first
pthread_create(&inputThread, &attr, input_thread, NULL);
pthread_join(inputThread, NULL);
pthread_join(lineSeparatorThread, NULL);
pthread_join(plusSignThread, NULL);
pthread_join(outputThread, NULL);
// Freeing up memory.
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
pthread_mutex_destroy(&mutex3);
pthread_cond_destroy(&readyBuffer1);
pthread_cond_destroy(&readyBuffer2);
pthread_cond_destroy(&readyBuffer3);
return 0;
}
And lastly, my #include statements and buffer variables.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <ctype.h>
#define BUFSIZE 50
// Buffers can hold up to 50 lines that can be 1000 characters.
char buffer1[BUFSIZE][1000]; //inputThread + lineSeparatorThread
char buffer2[BUFSIZE][1000]; //lineSeparatorThread + plus_sign_thread
char buffer3[BUFSIZE][1000]; //plus_sign_thread + output_thread
Its look like your'e missing compilation flag -pthread.
try to put the flag as last.
gcc test.c -o test -std .... -pthread
From man7:
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg);
Compile and link with -pthread.`
https://man7.org/linux/man-pages/man3/pthread_create.3.html
I am trying to compile a c program with a static library and its not working .
This is the error :
undefined reference to `calculatearea'
collect2.exe: error: ld returned 1 exit status .
The static files were made with the gcc / g++ compilers .
This is the main code :
#include <stdio.h>
#include <stdint.h>
int calculatearea(int a , int b);
int main()
{
int c = calculatearea(2,4);
printf("%d",c);
getchar();
return 0;
}
edit :
: screenshot of compiler error
From the above code we can see that you have declared the function int calculatearea(int a , int b); but have not written any definition for the same. and you are calling this function in the main. compiler is not finding the definition for the function calculatearea and giving error.
To solve this:
1) Write the definition for function calculatearea in the same file.
2) Make use of extern specifier with this function declaration and make sure that definition is present with the link library at the time of compilation.
3) As mentioned in the picture if the area.o have the definition of function calculatearea, then compile as below, this will generate a.out in linux:
gcc filename.c area.o
I am trying to make sense of a program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int main(int argc, char** argv) {
volatile double fShared = 0.0;
// create pthread structures - one for each thread
pthread_t t0;
pthread_t t1;
//Arbitrary pointer variables - void* is a pointer to anything
void *thread_res0;
void *thread_res1;
int res0,res1;
//create a new thread AND run each function
// we pass the ADDRESS of the thread structure as the first argument
// we pass a function name as the third argument - this is known as a FUNCTION pointer
// you might want to look at the man pages for pthread_create
res0 = pthread_create(&t0, NULL, do_this, (void*)"");
res1 = pthread_create(&t1, NULL, do_that, (void*)"");
// Two threads are now running independently of each other and this main function
// the function main is said to run in the main thread, so we are actually running
// The main code can now continue while the threads run - so we can simply block
res0 = pthread_join(t0, &thread_res0);
res1 = pthread_join(t1, &thread_res1);
printf ("\n\nFinal result is fShared = %f\n",fShared);
return (EXIT_SUCCESS);
}
It should be noted that do_this and do_that are functions created earlier in the program. I am getting the following errors:
seed#ubuntu:~/Programs$ Homework2OS.c
/tmp/cceiRtg8.O: in function 'main'
Undefined reference to 'pthread_create'
Undefined reference to 'pthread_create'
Undefined reference to 'pthread_join'
Undefined reference to 'pthread_join'
We were given this bit of code to fix. I have found elsewhere the format for the pthread_create constructor. Do I need to actually define it above the main? I was under the impression it was imported with the library.
I would also venture to guess that it has something to do with the fourth parameter? I understand that the first parameter is the location of the thread (defined above), the second is NULLed, the third is the function call but I do not quite understand what the fourth parameter is supposed to be.
What's wrong?
all the code imports is the header for the pthread library. (pthread.h)
What is missing is the linker needs to actually include the library for gcc the parameter -pthread is needed (AT THE END of the list of parameters to gcc.)
It needs to be at the end because the linker processes parameters in the order given on the command line and if the object files are not already processed, then there will not be any unresolved references for the linker to try to resolve via browsing the pthread library.
I.E. this is wrong:
gcc -g -o myprogram -lpthread myprogram.o
This is correct:
gcc -g -o myprogram myprogram.o -lpthread
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
undefined reference to pthread_create in linux (c programming)
I am trying to implement Thread chain in Ubuntu in C. When I compile the following code, I get the errors of Undefined reference to these thread library function even though I have added the header file.I am also getting segmentation fault error. Why is that? I am not accessing some uninitialized memory anywhere in program. Here is the code:
#include <stdio.h>
#include<stdlib.h>
#include <pthread.h>
void* CreateChain(int*);
int main()
{
int num;
pthread_t tid;
scanf("Enter the number of threads to create\n %d",&num);
pthread_create(&tid,NULL,CreateChain,&num);
pthread_join(tid,NULL);
printf("Thread No. %d is terminated\n",num);
return 0;
}
void* CreateChain(int* num )
{
pthread_t tid;
if(num>0)
{
pthread(&tid,NULL,CreateChain,num);
pthread_join(tid,NULL);
printf("Thread No. %d is terminated\n",*num);
}
else
return NULL;
return NULL;
}
I am getting following warnings and the Scanf prompt is not appearing for some reason.
Regards
The pthread.h header file provides a forward declaration of pthread functions. This tells the compiler than these functions exist and have a certain signature. It doesn't however tell the linker anything about where to find these functions at runtime.
To allow the linker to resolve these calls (decide where to jump to inside your code or in a different shared object), you need to link against the appropriate (pthread) library by adding
-pthread
to your build command line.
[Note that it is also possible to use -lpthread. This previous question expains why -pthread is preferable.]
There are various other issues with the code that will be worthy of attention
The scanf line should be split into printf("Enter number of threads\n");scanf("%d", &num); to get the user prompt displayed
The signature of CreateChain is wrong - it should take a void* argument instead. You can always do something like int num = *(int*)arg; inside the function to retrieve the number of threads.
The logic inside CreateChain looks wrong. You currently compare a pointer against 0 - I presume you mean to compare the number of threads instead? Also, if you don't decrement the number of threads to create somewhere, you'll end up with code that creates threads forever (or until you run out of handles depending on how the different threads get scheduled).
Try compiling like this below :
gcc -Wall -pthread test.c -o test.out
-pthread is an option to tell linker explicitly to resolve the symbols related to <pthread.h>
add -lpthread
gcc -o test test.c -lpthread
I have used the following code to create two threads:
//header files
#include <pthread.h>
struct thread_arg
{
int var1;
int var2;
};
void *serv_com(void *pass_arg)
{
struct thread_arg *con = pass_arg;
//required statements irrelevant to the issue
pthread_exit(NULL);
}
void *cli_com(void *pass_arg)
{
struct thread_arg *con = pass_arg;
//required statements irrelevant to the issue
pthread_exit(NULL);
}
int main()
{
pthread_t inter_com;
//necessary code
while(1)
{
th_err_s = pthread_create(&inter_com, NULL, serv_com, (void *)&pass_arg);
th_err_c = pthread_create(&inter_com, NULL, cli_com, (void *)&pass_arg);
if (th_err_s || th_err_c)
{
printf("Alert! Error creating thread! Exiting Now!");
exit(-1);
}
}
pthread_exit(NULL);
return 1;
}
Then I compiled the above code in linux using the following command:
gcc -o sample sample.c
It returned the following error message:
inter.c:(.text+0x374): undefined reference to `pthread_create'
inter.c:(.text+0x398): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
What should I do to correctly compile this file. I am sure it is no syntax error or anything since when I commented off everything inside the while loop, the program was compiling correctly and I verified that the pthread_create syntax is correct. Do I have to issue some other command to compile the file?
EDIT: Is there any problem with the creating of two threads in the above code? The program is just exiting with the error message once it is running. What can be the possible issue and how can I solve it? Thanks in advance.
Try doing this :
gcc -lpthread sample.c
or
gcc -pthread sample.c
above 2 commands will directly create executable a.out
Answer after edit:
1) Wait for the two threads to join main thread using call
int pthread_join(pthread_t thread, void **value_ptr);
2) Create both threads with different ids
3) Also avoid calling pthread_exit from main() if you can, although there is no harm doing that
4) you are calling pthread_create in while(1) this will create infinite threads .. I do not know what are you trying to achieve .
Link to pthread Library when compiling...
gcc -o sample -lpthread sample.c
I am not too sure myself but I would think you could do something like
pthread_t inter_com, inter_com2;
and
th_err_s = pthread_create(&inter_com, NULL, serv_com, (void *)&pass_arg);
th_err_c = pthread_create(&inter_com2, NULL, cli_com, (void *)&pass_arg);
I think it should give you 2 ids of threads. But careful when sharing variables etc between threads. But am glad you resolved it yourself.