It's an ecological niche. All animals are in competition for food sources. Lots of other animals can eat from lower branches, but only giraffes (and elephants by a different mechanism) can eat the top leaves. Acacia trees defend themselves on sides and bottom with big thorns, which is another incentive.
Incidentally, evolution works by mutation then dieback ... so the giraffes didn't "see the need" to grow long necks, then change to do it, they changed at random, then it turned out that the ones with long necks had an advantage, didnt starve, bred succesfully etc. Slowly this leads to speciation.