I picked up the following demo off the web from https://computing.llnl.gov/tutorials/pthreads/
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
But when I compile it on my machine (running Ubuntu Linux 9.04) I get the following error:
corey#ubuntu:~/demo$ gcc -o term term.c
term.c: In function ‘main’:
term.c:23: warning: incompatible implicit declaration of built-in function ‘exit’
/tmp/cc8BMzwx.o: In function `main':
term.c:(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
This doesn't make any sense to me, because the header includes pthread.h, which should have the pthread_create function. Any ideas what's going wrong?
For Linux the correct command is:
gcc -pthread -o term term.c
In general, libraries should follow sources and objects on command line, and -lpthread is not an "option", it's a library specification. On a system with only libpthread.a installed,
gcc -lpthread ...
will fail to link.
Read this or this detailed explanation.
For Linux the correct command is:
gcc -o term term.c -lpthread
you have to put -lpthread just after the compile command,this command will tell to the compiler to execute program with pthread.h library.
gcc -l links with a library file.Link -l with library name without the lib prefix.
in eclipse
properties->c/c++Build->setting->GCC C++ linker->libraries in top part add "pthread"
Running from the Linux terminal, what worked for me was compiling using the following command (suppose the c file I want to compile is called test.c):
gcc -o test test.c -pthread
Hope it helps somebody!
If you are using cmake, you can use:
add_compile_options(-pthread)
Or
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
I believe the proper way of adding pthread in CMake is with the following
find_package (Threads REQUIRED)
target_link_libraries(helloworld
${CMAKE_THREAD_LIBS_INIT}
)
Acutally, it gives several examples of compile commands used for pthreads codes are listed in the table below, if you continue reading the following tutorial:
https://computing.llnl.gov/tutorials/pthreads/#Compiling
Compile it like this : gcc demo.c -o demo -pthread
In Visual Studio 2019 specify -pthread in the property pages for the project under:
Linker -> Command Line -> Additional Options
Type in -pthread in the textbox.
You need to use the option -lpthread with gcc.
you need only Add "pthread" in proprieties=>C/C++ build=>GCC C++ Linker=>Libraries=> top part "Libraries(-l)".
thats it
check man page and you will get.
Compile and link with -pthread.
SYNOPSIS
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
Compile and link with -pthread.
....
Since none of the answers exactly covered my need (using MSVS Code), I add here my experience with this IDE and CMAKE build tools too.
Step 1: Make sure in your .cpp, (or .hpp if needed) you have included:
#include <functional>
Step 2 For MSVSCode IDE users:
Add this line to your c_cpp_properties.json file:
"compilerArgs": ["-pthread"],
Step 2 For CMAKE build tools users:
Add this line to your CMakeLists.txt
set(CMAKE_CXX_FLAGS "-pthread")
Note: Adding flag -lpthread (instead of -pthread) results in failed linking.
From man gcc,
-pthread
Define additional macros required for using the POSIX threads library.
You should use this option consistently for both compilation and linking.
This option is supported on GNU/Linux targets,
most other Unix derivatives,
and also on x86 Cygwin and MinGW targets.
It is correct that -pthread is an option and the best way to handle this.
There are statements in some answers that it generates different compiled code. This is misleading.
If you wish to duplicate -pthread, you could use -lpthread -D_REENTRANT=1. So there are two things going on with the -pthread option.
Indeed it links with the pthread library as many answers express. Also, the order of the pthread library is important because it may override some weak symbols. So a correct version using -lpthread may need to have it multiple times on the command line.
The other important part is the _REENTRANT define. Note, that this is in the implementation namespace. Some people may care for portability and other not. However, it is very important that it is defined as the first thing in the compilation unit. This symbol will alter the way that many system headers files are parsed.
You can include #define _REENTRANT 1 at the top of every source file, but it is much easier to have it on the command line. Again, the -pthread is the best way to achieve this. Also, gcc may change the way this is implemented in the future. However, I think it is important for programmers to understand what is going on.
term.c: In function ‘main’: term.c:23: warning: incompatible implicit
declaration of built-in function ‘exit’
You never included <stdlib.h>, where exit() is declared. Also, I think newer versions of gcc have removed the need for _REENTRANT.
Why features.h?
Example on godbolt, without -pthread.
So, it is NOT generating different code. Ie, the backend of the compiler is NOT different. It is only conditional compilation and linking to different libraries. It does not generate 'lock free' code or add appropriate machine barriers because you have used this option.
In Anjuta, go to the Build menu, then Configure Project.
In the Configure Options box, add:
LDFLAGS='-lpthread'
Hope it'll help somebody too...
Sometimes, if you use multiple library, check the library dependency.
(e.g. -lpthread -lSDL... <==> ... -lSDL -lpthread)
I am trying to compile my file using make, however, it shows the following error
/usr/bin/gcc -march=i586 -m32 -fno-builtin -fno-stack-protector -nostdlib -c -Wall -O0 -DBSDURG -DVERSION=\""`cat version`"\" -I../include -o binaries/farm.o ../system/farm.c
Loading object files to produce GRUB bootable xinu
binaries/farm.o: In function `initialize':
farm.c:(.text+0x2c): undefined reference to `malloc'
After some searching, people have mentioned that not include "stdlib.h" may be the cause, however, I have included it
/* farm.c - definition of farmer and vegetarian lab */
#include <xinu.h>
#include "farm.h"
#include <stdio.h>
#include <stdlib.h>
Anyone some idea what are the possible causes?
Many Thanks!
-nostdlib flag means "don't link with standard C library". malloc is libc function. Either you link with libc (by removing -nostdlib), or, if that's a requirement, - implement another malloc (or don't use this function).
Include files are for compilation time resolution of functions not link time resolution of symbols.
That is a link time issue.
Your problem is most likely caused by the -nostdlib since you have told gcc not to include any of the normal standard library functions during linking. (It might be -fono-builtin but I don't think so.)
You either need to provide your own implementation of whatever standard functions you need (in this case malloc) or manually link with whatever library includes malloc (-lgcc perhaps?) or drop -nostdlib from your compilation and linking line.
I want to static link libray which I included (such as stdio) with gcc, so I use the -static options.
My environment is ubuntu 10.10.
gcc version is 4.4.5.
the compile command I used is : gcc -static -o output.out input.c
the following is my source code.
include
int main(){
printf("hello world");
return 0;
}
After I compile it and use the -static option, I objdump the executable file.
and I found out that the printf is actually called _IO_printf.
And I write another program, the following is the souce code.
include
int main(){
return 0;
}
I compile this source code with the same option and objdump the new executable file.
However, I can't find the _IO_printf.
My question is why I can't fine _IO_printf in the second case. I have static linked the libray which I included.
Can someone plz help me solve this problem, thx.
A linker doesn't just put object files and libraries together. It creates links between the different parts. So if there is an unresolved symbol (e.g. function or variable) in one unit, it looks for it in other units and makes the connection.
Since the second program doesn't call printf, the linker does not need to resolve that symbol. So there is no point adding that function to the executable (it'll just sit there and take space). The linker can see what's missing, and should (normally) add only what's missing down to some practical granularity.
I have to build a "proof of concept" using cgicc on Windows. But currently I am unable to build cgicc. The current release of cgicc v3.2.9 won't build neither in MinGW (gcc v4.5.0 / v3.4.5) nor Cygwin (gcc v4.3.4-3).
By using gcc v3.4.5 and automake in MinGW I got:
HTMLAttributeList.cpp:51: internal compiler error: in rest_of_handle_final, at toplev.c:2067
Please submit a full bug report, with preprocessed source if appropriate.
Using gcc v4.3.4 and automake gives for Cygwin:
In file included from CgiEnvironment.cpp:36:
../cgicc/CgiEnvironment.h:52: error: explicit instantiation of 'class std::vector<cgicc::HTTPCookie, std::allocator<cgicc::HTTPCookie> >' in namespace 'cgicc'
which does not enclose namespace 'std')
and for gcc v4.5.0 in MinGW:
../cgicc/CgiEnvironment.h:52:33: error: explicit instantiation of 'class std::vector<cgicc::HTTPCookie>' in namespace 'cgicc' (which does not enclose namespace
'std')
I tried to ignore the Automake and Autoconf scripts. I set up Eclipse-CDT for using the apropriate compiler switches (I also tried Code::Blocks):
-DHAVE_CONFIG_H -DWIN32 -I.. -Wall -W -pedantic -g -DDLL_EXPORT -DPIC -DCGICC_EXPORTS
But again I got:
explicit instantiation of 'class std::vector<cgicc::HTTPCookie, std::allocator<cgicc::HTTPCookie> >' in namespace 'cgicc' (which does not enclose namespace 'std') CgiEnvironment.h /cgicc/cgicc line 52
CgiEnvironment.h:51 to line 53 contains the ifdef WIN32:
#include <string>
#include <vector>
#include <cstdlib>
namespace cgicc {
...
#ifdef WIN32
template class CGICC_API std::vector<HTTPCookie>;
#endif
...
}
What goes wrong? Any suggestions?
Now I can compile cgicc. Thanks to a very good friend of mine, Vlad Lazarenko and some hours of investigation. But I have to do some major changes.
My friend helped me to go on the right way by understanding the main issue. He and Vlad Lazarenko gave me a good direction to investigate the __declspec(). This is a feature of Microsoft compilers which are now supported in gcc.
During investigation I stumbled over a post with migration hints for GCC3.4.3 to GCC4.1.2. So I moved the explicit instantiation of the templates behind the declared namespace in following headers:
Cgicc.h
CgiEnvironment.h
HTMLAttributeList.h
HTMLElementList.h
Next I discovered a strange behaviour while checking different compiler switches and other things regarding my build environment. During investigatiopn of cgicc header files the defined -DCGICC_EXPORTS becomes sometimes undefined (expansion is shown by Eclipse CDT). So I changed CgiDefs.h from:
// export library symbols
#ifdef CGICC_EXPORTS
# define CGICC_API __declspec(dllexport)
#else
# define CGICC_API __declspec(dllimport)
#endif
to
# define CGICC_API __declspec(dllimport)
At the end I changed the compiler switches to
-DWIN32 -DCGICC_EXPORTS -DHAVE_CONFIG_H -I.. -O0 -g3 -Wall -c -fmessage-length=0 -std=gnu++98. Most important is -std=gnu++98. Without gnu extensions __declspec() wont generate any symbols - even for a static library. I do not understand why I need that for a static library because the symbols should be in their object files which are packet into libcgicc.a.
Now some further questions:
Do anyone know a mechanism how CGICC_EXPORTS can became undefined
without #undef CGICC_EXPORTS and without -UCGICC_EXPORTS?
Why I have to use gnu extensions? I thought the defaults are independend.
Why do I have to use __declspec(dllexport) for a static library?
Why it is not enough to use the object files of a static library? Let me ask the same
in a different way: Why are no symbols found if I try to link object files of a static
library?
What is the advantage/disadvantage of "implicit template instantiation and vague
linkage" versus "explicit template instantiation"?
The CGICC_API should be either defined as __declspec(dllimport) or __declspec(dllexport).
It looks like that DLL_EXPORT macro that gets defined in command line should affect that, but it doesn't.
My guess is that some header handling it is not included. See this and that for more information.
I have a mixture of c and c++ files compiling under g++. As explained in:
What is the difference between g++ and gcc?
The c files are being compiled as c++ with the g++ command line. Not huge problem but migrating over to gcc will allow th c files to compile as c files and the c++ file to compile as c++.
What -I includes or -L libraries do I need to add to the gcc command line, that the g++ command line is including by default?
You shouldn't need to add any includes or libraries beyond what you already have.
Whatch out for C functions being called from C++ code - you need to tell the C++ compiler those are C functions so the program is linked correctly and works.
The standard practice is to add the following directives to all your C headers being included in C++ files:
#ifdef __cplusplus
extern "C" {
#endif
... C header contents go here ...
#ifdef __cplusplus
}
#endif
More info here: http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html
You shouldn't need to add any. If it's using C++ it should automatically bring in C++ libraries.
If not, you'll want -lstdc++ (and if you're still getting undefined references, -lc for the libc). Don't forget -lm if you use math functions.
GCC can determine which language a file is in based on the file extension. However, GCC does not automatically link in run time support for any language other than C. In practice that means you can compile C++ programs using gcc instead of g++ but you'll need to add the -lstdc++ directive:
#include <iostream>
int main()
{
std::cout << "Hello world\n";
}
g++ hello.cc
gcc hello.cc -lstdc++
More accurately, you will need to specify -lstdc++ if you you use the standard library, exceptions, operator new, or RTTI. For instance, try compiling the following without -lstdc++:
int main()
{
try {
throw 1;
}
catch (int i)
{
return i;
}
}
Please note that STL containers (including std::strings) use operator new by default. Strictly speaking you should be able to use the algorithms (std::min, std::find_first_of, etc.) binders and a few other things in the standard library without -lstdc++ but for the most part you might as well include it (the linker will ignore any libraries that you don't actually link to).
Why not compile the c objects with gcc and the c++ with g++ and then when you link, link using the g++?