Lucas
Lucas

Reputation: 134

Strange error in C OpenMP parallel program

I'm studying patterns for parallel programming. I was going through the examples in the book but one example failed to compile. Here's the code:

#include <stdio.h>
#include <math.h>
#include <omp.h>

int main() {

int i;
int num_steps = 1000000;
double x, pi, step, num = 0.0;

step = 1.0/(double) num_steps;

#pragma omp parallel for private(x) reduction(+:sum)
    for(i=0; i < num_steps; i++) {
        x = (i+0.5) * step;
        sum+= 4.0/(1.0+x*x);
    }

pi = step *sum;
printf("pi %lf\n", pi);
return 0;
}

enter image description here

I'm new to PP so I don't know what I am doing wrong.

Upvotes: 1

Views: 158

Answers (1)

shuttle87
shuttle87

Reputation: 15954

There's no variable for sum declared in the code so when the compiler gets to the line:

#pragma omp parallel for private(x) reduction(+:sum)

It doesn't know what sum is and gives you the compilation error you ran into.

To fix this you need to declare the sum variable first:

double sum = 0.0;
#pragma omp parallel for private(x) reduction(+:sum)

As pointed out in the comments the problem is as the result of a typo:

double x, pi, step, num = 0.0; //num should be sum here

By compiling with all warnings -Wall compiler option for gcc you would get a warning about an unused variable num which would fairly quickly point out the source of the problem here.

Upvotes: 1

Related Questions