title: How to compile openmp using g++
body: <p>I have a problem about the openmp compiling.</p>
  
  <p>Like the following code:</p>
  
  <pre><code>#include &lt;iostream&gt; 
  #include &lt;pthread.h&gt;
  #include &lt;omp.h&gt;
  #include &lt;semaphore.h&gt;
  #include &lt;stack&gt;
  using namespace std;
  sem_t empty,full;
  stack&lt;int&gt; stk;
  void produce(int i)
  {
      {
      sem_wait(&amp;empty);
              cout&lt;&lt;"produce "&lt;&lt;i*i&lt;&lt;endl;
              stk.push(i*i);
      sem_post(&amp;full);
      }
  }
  void consume1(int &amp;x)
  {
      sem_wait(&amp;full);
              int data=stk.top();
              stk.pop();
              x=data;
      sem_post(&amp;empty);
  }
  void consume2()
  {
      sem_wait(&amp;full);
              int data=stk.top();
              stk.pop();
              cout&lt;&lt;"consume2 "&lt;&lt;data&lt;&lt;endl;
      sem_post(&amp;empty);
  }
  int main()
  {
      sem_init(&amp;empty,0,1);
      sem_init(&amp;full,0,0);
      pthread_t t1,t2,t3;
      omp_set_num_threads(3);
      int TID=0;
      #pragma omp parallel private(TID)
      {
              TID=omp_get_thread_num();
              if(TID==0)
              {
              cout&lt;&lt;"There are "&lt;&lt;omp_get_num_threads()&lt;&lt;" threads"&lt;&lt;endl;
              for(int i=0;i&lt;5;i++)
                      produce(i);
              }
              else if(TID==1)
              {
                      int x;
                      while(true)
                      {
                              consume1(x);
                              cout&lt;&lt;"consume1 "&lt;&lt;x&lt;&lt;endl;
                      }
              }
              else if(TID==2)
              {
                      int x;
                      while(true)
                      {
                              consume1(x);
                              cout&lt;&lt;"consume2 "&lt;&lt;x&lt;&lt;endl;
                      }
              }
      }
      return 0;
  }
  </code></pre>
  
  <p>Firstly, I compile it using:</p>
  
  <pre><code>g++ test.cpp -fopenmp -lpthread
  </code></pre>
  
  <p>And, I got the right answer, there are 3 threads totally.</p>
  
  <p>But, when I do the compile like this:</p>
  
  <pre><code>g++ -c test.cpp -o test.o
  g++ test.o -o test -fopenmp -lpthread
  </code></pre>
  
  <p>there is just only ONE thread.</p>
  
  <p>Anyone can tell me how to compile this code correctly. Thankyou in advance.</p>