compiling C code produces an error: “somefile.h: No such file or directory”. Why?

The error occurs if a header file is not present in the standard include file directories used by gcc/g++/nvcc etc. A similar problem can occur for libraries:

/usr/bin/ld: cannot find library

This happens if a library used for linking is not present in the standard library directories.

By default, gcc based compilers search the following directories for header files:

/usr/local/include/
/usr/include/

and the following directories for libraries:

/usr/local/lib/
/usr/lib/

The list of directories for header files is often referred to as the include path, and the list of directories for libraries as the library search path or link path.

The directories on these paths are searched in order, from first to last in the two lists above. For example, a header file found in ‘/usr/local/include’ takes precedence over a file with the same name in ‘/usr/include’. Similarly, a library found in ‘/usr/local/lib’ takes precedence over a library with the same name in ‘/usr/lib’.

When additional libraries are installed in other directories it is necessary to extend the search paths, in order for the libraries to be found. The compiler options -I and -L add new directories to the beginning of the include path and library search path respectively.

For example compiling the “test.cc” code below:

#include <stdlib.h>
#include <stdio.h>
#include "cuda_runtime.h"
int main(void)
{
  int num_elements = 16;
  int num_bytes = num_elements * sizeof(int);

  int *device_array = 0;
  int *host_array = 0;

  host_array = (int*)malloc(num_bytes);
  cudaMalloc((void**)&device_array, num_bytes);
  cudaMemset(device_array, 0, num_bytes);
  cudaMemcpy(host_array, device_array, num_bytes, cudaMemcpyDeviceToHost);
  for(int i = 0; i < num_elements; ++i)
    printf("%d", host_array[i]);
  free(host_array);
  cudaFree(device_array);
  return 0;
}

 

With “nvcc test.cc -o testcode” will produce:

test.cc:3:26: error: cuda_runtime.h: No such file or directory
test.cc: In function ‘int main()’:
test.cc:13: error: ‘cudaMalloc’ was not declared in this scope
test.cc:14: error: ‘cudaMemset’ was not declared in this scope
test.cc:15: error: ‘cudaMemcpyDeviceToHost’ was not declared in this scope
test.cc:15: error: ‘cudaMemcpy’ was not declared in this scope
test.cc:19: error: ‘cudaFree’ was not declared in this scope

With “nvcc test.cc -I/usr/local/cuda-5.5/include -o test” will produce:

/usr/bin/ld: cannot find -lcudart_static
collect2: ld returned 1 exit status

With “nvcc test.cc -I/usr/local/cuda/include -L/usr/local/cuda/targets/x86_64/lib -o test”
will WORK!