Simvik

Build in dependency order

Order targets so each is built after what it depends on, and detect cycles. A medium embedded C problem (Make and CMake for embedded), run and graded in the…

medium · Make and CMake for embedded · make · build · graphs

A build tool must build every target after the targets it depends on. Targets are numbered 0 to n - 1; deps[i] is a bitmask of the targets that target i depends on.

Write build_order(deps, n, order): fill order with all n targets so that every target comes after its dependencies, choosing the lowest-numbered ready target each time (so the answer is unique). Return n, or -1 if there is a dependency cycle.

Starter code

int build_order(const uint32_t *deps, int n, int *order) {
  (void)deps;
  for (int i = 0; i < n; i++) order[i] = i;
  return n;
}

Example tests

A firmware image

/* 0 app.elf needs 1 main.o, 2 drivers.a; 2 needs 3 gpio.o, 4 uart.o */
uint32_t deps[5] = { (1u << 1) | (1u << 2), 0, (1u << 3) | (1u << 4), 0, 0 };
show(deps, 5);

Expected output:

1 3 4 2 0

A chain

uint32_t deps[4] = { 1u << 1, 1u << 2, 1u << 3, 0 };
show(deps, 4);

Expected output:

3 2 1 0

Learn it first