WASHINGTON — United States Special Operations troops are forming elite counterterrorism units in four countries in North and West Africa that American officials say are pivotal in the widening war against Al Qaeda’s affiliates and associates on the continent, even as they acknowledge the difficulties of working with weak allies.

The secretive program, financed in part with millions of dollars in classified Pentagon spending and carried out by trainers, including members of the Army’s Green Berets and Delta Force, was begun last year to instruct and equip hundreds of handpicked commandos in Libya, Niger, Mauritania and Mali.

The goal over the next few years is to build homegrown African counterterrorism teams capable of combating fighters like those in Boko Haram, the Islamist extremist group that abducted nearly 300 Nigerian schoolgirls last month. American military specialists are helping Nigerian officers in their efforts to rescue the girls.

“Training indigenous forces to go after threats in their own country is what we need to be doing,” said Michael A. Sheehan, who advocated the counterterrorism program last year when he was the senior Pentagon official in charge of Special Operations policy. Mr. Sheehan now holds the distinguished chair at the Combating Terrorism Center at West Point.