Moving loop in ld function to C++