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"
7
  • Only match lines that begin with #, maybe? Commented Mar 26, 2017 at 14:33
  • @larsks i wont to get this - /* some comment*/#include <stdlib.h> to Commented Mar 26, 2017 at 14:34
  • @user401689 do you wan't something like sed -n 's/.*\(<.*>\).*/\1 /p' main.c ? Commented Mar 26, 2017 at 14:34
  • @val0x00ff this is no correct for this - /* #include <stdlib.h> */, i wont take in fact include libraries Commented Mar 26, 2017 at 14:39
  • 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 Commented Mar 26, 2017 at 14:41

1 Answer 1

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).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.