1

I need to extract all included libraries in a C file, but I got some problems. My solution for this is so:

grep -oP '#(?:\/\*\w*\*\/|)include(?:\/\*\w*\*\/|\s*)"\w*.h"|<\w*.h>' main.c

This regex takes library when it is in comment, for example

/*#include <stdlib.h>*/

and I don't know how to make that script gives me only name of library without #include

How to fix my regex to it work right?

UPD:

main.c

#include  "string.h"
#include <stdlib.h>
 #include "math.h"
    #include "stdint.h"
#/*comment*/include /*comment*/ <fenv.h>  
//#include <iostream>
#/**/include "something.h"
/* comment */#include "float.h"
/*#include "library.h"*/
int main() {

}

What I want:

"string.h"
<stdlib.h>
"math.h"
"stdint.h"
<fenv.h>
"something.h"
"float.h"
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Shmuser
  • 111
  • Only match lines that begin with #, maybe? – larsks Mar 26 '17 at 14:33
  • @larsks i wont to get this - /* some comment*/#include <stdlib.h> to – Shmuser Mar 26 '17 at 14:34
  • @user401689 do you wan't something like sed -n 's/.*\(<.*>\).*/\1 /p' main.c ? – Valentin Bajrami Mar 26 '17 at 14:34
  • @val0x00ff this is no correct for this - /* #include <stdlib.h> */, i wont take in fact include libraries – Shmuser Mar 26 '17 at 14:39
  • @user401689 it would be good idea to post sample of input lines and corresponding output for whatever cases you can think of... that way it would be clearer than possible ambiguity... – Sundeep Mar 26 '17 at 14:41
  • 1
    If you really have lines with comments before include-directives, but you only want the directives itself (as opposed to full lines or other context), you need to remove the comments first, and then look for the directives. Given all the quirks of the C language, that's not as trivial as it seems. #if blocks will be your next problem – ilkkachu Mar 26 '17 at 14:41
  • Now this guy got me lost. plunk – Valentin Bajrami Mar 26 '17 at 14:42

1 Answers1

6

You should ask the compiler (or rather, the C pre-processor) to do the work for you:

gcc -M main.c

This will produce a Makefile-style dependency with all the headers included by main.c (including those included transitively). It will correctly handle comments and other pre-processor directives (#if, #ifdef and so on).

Stephen Kitt
  • 434,908