The gravitational force is a conservative force and hence we can define a gravitational potential energy associated with this conservative force field.
Two masses m1 and m2 are initially separated by a distance r’. Assuming m1 to be fixed in its position, work must be done on m2 to move the distance from r’ to r.

To move the mass m2 through an infinitesimal displacement \(d\vec r\) from \(\vec r\) to \(\vec r\) + \(d\vec r\), work has to be done externally. This infinitesimal work is given by

The work is done against the gravitational force, therefore

Substituting equation (2) in (1), we get

Thus the total work for displacing the particle from r’ to r is

This work done W gives the gravitational potential energy difference of the system of masses m1 and m2 when the seperation between them are r and r’ respectively.

Case 1: If r < r’ : Since gravitational force is attractive, m2 is attracted by m1. Then m2 can move from r’ to r without any external Work. Here work is done by the system spending its internal energy and hence the work done is said to be negative.
Case 2: If r > r’: Work has to be done against gravity to move the object from r’ to r. Therefore work is done on the body by external force and hence work done is positive.