How to Tell Clang to Read Include Directories
Where Does GCC Look to Find its Header Files?
Partly past convention and partly by design, C programs are split into source files that depict the functionality of the programme itself and header files that describe how to invoke that functionality from other source files. Technically speaking, you tin write a complete and useful C program without ever creating or referring to a header file — this is actually viable when writing embedded apps — but practically, yous're going to probably need to at least import a few. You tin can't fifty-fifty read a file or write to the console without importing <stdio.h>, for example.
include
-ing a header file in a C program actually means copying the contents of some other file in the current one. The strange-looking construct in listings one and 2 compile and piece of work correctly:
printf( "%d\due north", i );
List 1: increment.c
#include <stdio.h> int chief( int argc, char *argv[] ) { int i = 0; for ( i = 0; i < ten; i++ ) { #include "increment.c" } }
List 2: count.c
Nobody ever codes this way (I promise...) but since the C preprocessor's #include
directive merely means "copy the contents of the named file into this one before compiling", y'all could.
In practical utilize, though, #include
is used to copy in header files that depict other modules which will be linked and referred to inside the electric current source file. C includes dozens of standard header files for I/O, math, concurrency, string manipulation, etc. If you refer to one, its contents must be copied into the current source file earlier it can be processed. So, where does the compiler look to find these files? The primeval description of the C programming language, Kernighan and Ritchie's book "The C Programming Linguistic communication" (AKA K&R), talks about the preprocessor in chapter 4:
File inclusion makes it easy to handle collections of#defines
and declarations (amidst other things). Any source line of the formor#include "filename"
is replaced past the contents of the file filename. If the filename is quoted, searching for the file typically begins where the source programme was constitute; if it is not found at that place, or if the proper noun is enclosed in < and >, seaching follows an implementation-defined rule to detect the file.#include <filename>
While not an official standard, M&R suggested 2 dissimilar ways to bespeak to the compiler where to look for a header file. The first was to enclose the name of the header file in double quotes, e.g. "header.h"
. In this case, the compiler should (typically) look for the header in the same directory as the source file. Otherwise, the search should be "implementation-defined". Well, that'southward not very informative. K&R was published in 1978, but C was standardized by ANSI in 1983. So what does the standard say well-nigh header file inclusion?
The official C standard in section half dozen.10.ii, "Source file inclusion", states:
A preprocessing directive of the classcauses the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner.#include "q-char-sequence" new-line
The standard actually says less virtually where to look for header files than K&R does! Technically speaking, it'southward impossible to write a portable C program consisting of less than one source file, since the compiler can be standards compliant while searching for header files anywhere it cares to.
Although Apple seems to take nudged the world in the direction of LLVM, for decades, GCC was the de facto standard for C compilation until very recently. Sometimes you had to employ a vendor-specific compiler like Microsoft's, but GCC mostly blazed the trail for standardizing the non-standard parts of the C progamming linguistic communication. And then what is the "implementation-defined" GCC fashion for header file incluion? As it turns out, although information technology mostly does what you want it to in most cases, it can be pretty complex and compiler flags can make radical changes to it.
In the simplest (theoretical) case, you have a single source file and a single header file, both in the aforementioned directory. In this case, GCC'southward job seems easy; it just looks in the current directory, finds the header file, and compiles. But actually, in that location'southward even a bit of a twist here. This complication arises because the behavior differs when you use quotes vs. angle brackets. If y'all use quotes, the electric current directory is searched first. If the header file isn't found, then the angle-bracket search path is used. Yous can verify this by actually "overriding" stdio.h
#define SEEK_SET 12
Listing iii: overridden stdio.h
If you include this file in the aforementioned directory as source.c
:
#include <stdio.h> int primary( int argc, char *argv[] ) { printf( "SEEK_SET = %d\n" ); }
List 4: arrangement search path
And compile and run this, you'll meet:
$ ./a.out SEEK_SET = 0
The compiler found the system re-create of stdio.h
instead of my "override". However, if I alter the #include
to employ single quotes: #include "stdio.h" int master( int argc, char *argv[] ) { printf( "SEEK_SET = %d\northward" ); }
Listing five: organization search path
The output becomes:
$ ./a.out SEEK_SET = 12
I too got a compiler alert nigh an incompatible implicit declaration of built-in function 'printf' — my new stdio.h
didn't declare it, but of course the linker still found it.
So, if a header file is not institute in the current directory, where does it look? The GCC documentation states:
GCC looks in several unlike places for headers. On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with#include
<file> in:/usr/local/include libdir/gcc/target/version/include /usr/target/include /usr/include
just that'due south sort of a wishy-washy answer (and also incomplete). Surely there must be a style to get GCC to tell you exactly where it'due south going to end up looking for its header files? Well, although it's convenient to recollect of GCC as a unmarried monolithic application that takes in source code files and spits out working programs, it's technically a collection of other programs which concatenation together to produce the concluding compiled object file. The first of these is CPP
, short for C Pre-Processor, whose job is to expect for compiler directives like #include
and alter the source code as specified by them; in the case of include, by copying the contents of some other file into the current one. Y'all tin can see where it looks for these files by passing it the -v
flag:
$ cpp -v ... #include "..." search starts hither: #include <...> search starts hither: /usr/local/include /usr/lib/gcc/x86_64-linux-gnu/4.iv.five/include /usr/lib/gcc/x86_64-linux-gnu/4.4.5/include-fixed /usr/include/x86_64-linux-gnu /usr/include
this path is actually built into CPP (which is office of GCC) at compile time; if for whatever reason you end upwardly deleting 1 of those directories, it will nevertheless be checked for on each compile. Each directory is searched in the society it's listed hither; if a file is constitute in /usr/local/include
, the next iii directories won't be checked. This beliefs is of import — detect the include-stock-still
directory in the search path? On my arrangement, it includes ii files: limits.h
and syslimits.h
. Both of these files also announced in /usr/include
; however, GCC will not operate correctly if it finds the copies from the /usr/include
directory later in its search path. In that location are a couple of ways you lot can manipulate this directory structure. The simplest is by providing the compiler flag -I
. -I
is followed by an absolute or relative (to the current directory) path, with no spaces, and inserts the named directory at the showtime of the "bending-subclass" search path. Thus, if you create a directory headers
, copy the "overridden" stdio.h
from list iii into information technology, and invoke gcc
with:
gcc -Iheaders source.c
the output volition show SEEK_SET as 12 even if you #include stdio.h
with angle brackets every bit in listing 4. cpp -v
verifies that the -I
'ed directory is starting time in the search path:
$ cpp -Iheaders -v ... #include "..." search starts here: #include <...> search starts hither: headers /usr/local/include /usr/lib/gcc/x86_64-linux-gnu/4.4.five/include /usr/lib/gcc/x86_64-linux-gnu/4.4.5/include-stock-still /usr/include/x86_64-linux-gnu /usr/include
Merely expect — earlier I said that GCC will non compile correctly if information technology picks up limits.h
from /usr/include
. So what happens if I endeavour to forcefulness /usr/include
to be the showtime directory in the list via: $ cpp -I/usr/include
? Equally it turns out, GCC will ignore me in this case: $ cpp -I/usr/include -5 ... ignoring duplicate directory "/usr/include" as information technology is a non-system directory that duplicates a system directory #include "..." search starts here: #include <...> search starts hither: /usr/local/include /usr/lib/gcc/x86_64-linux-gnu/4.4.five/include /usr/lib/gcc/x86_64-linux-gnu/4.4.v/include-fixed /usr/include/x86_64-linux-gnu /usr/include
There is no style to change this search social club other than to recompile GCC itself. Yous can laissez passer in the -nostdinc
pick which will remove all of these directories from the search path: $ cpp -I/usr/include -v ... #include "..." search starts hither: #include <...> search starts here:
But in that location are merely a few skilful reasons why y'all'd want to practise that (compiling the Linux kernel is one case). Other than -nostdinc
, GCC does non give you a mode to remove a directory from the search path in one case it's been added. If y'all want to add multiple directories to the search path, you specify the -I
directory multiples times. These new directories are added to the beginning of the search path, in the lodge that they're presented on the command line. If you lot accept a lot of paths that you need to specify repeatedly, GCC looks for an surroundings variable called CPATH
that has the same effect as include -I
multiple times, once for each colon- separated path in the proclamation:
$ Consign CPATH=hdr1:hdr2 $ cpp -v ... #include <...> search starts here: hdr1 hdr2 /usr/local/include ...
If you combine CPATH
with -I
flags, -I
takes precedence:
$ EXPORT CPATH=hdr1:hdr2 $ cpp -Ihdr3 -v ... #include <...> search starts hither: hdr3 hdr1 hdr2 /usr/local/include ...
In full general, though, you should probably never use the CPATH
environs variable, since you'll end up creating non-portable source lawmaking; specify a Makefile
instead. If yous look at all of the CPP search directory examples hither, you'll notice that they ever first with:
#include "..." search starts here:
And immediately jumping down to the angle-bracket search path, implying that goose egg is searched for quoted includes. Equally we know from experimentation, all the same, this search does include the current directory; GCC really does allow you to modify this search path as well, with the -iquote
compiler flag.
$ cpp -iquote hdr1 -v ... #include "..." search starts hither: hdr1 #include <...> search starts here: /usr/local/include /usr/lib/gcc/x86_64-linux-gnu/4.iv.five/include /usr/lib/gcc/x86_64-linux-gnu/iv.4.5/include-fixed /usr/include/x86_64-linux-gnu /usr/include
Here's an edge case that bit me last calendar week. Consider this directory construction:
base of operations/Makefile base/shared.c base of operations/cadre.h base/core.c override/Makefile override/cadre.c override/cadre.h
What I'g trying to exercise here is to generate two unlike executables - base
and override
. I want a different version of core.h
in each, but I desire to reuse shared.c
in each. So my Makefile in override looks similar this:
override: ../base/shared.c cadre.c cadre.h gcc -o override ../base of operations/shared.c cadre.c
The top of shared.c
looks like this: #include "cadre.h"
Naively, I causeless that shared.c
would compile with the version of core.h
from the override
directory, since that'south the "current working directory". As information technology turns out, no — GCC
considers ../base
the current working directory for that compilation unit because that'southward where it was establish. I spent a lot of fourth dimension banging my head confronting the keyboard trying to figure out what was going on hither, since the problem manifested itself as a memory corruption quite a ways into the execution of the awarding. One solution would be the -iquote
compiler directive... although I think if y'all find yourself manipulating the quote search path this manner, it's time to rethink your application construction (and, in my instance, I did). Add a comment:
Completely off-topic or spam comments will be removed at the discretion of the moderator.
Yous may preserve formatting (e.g. a lawmaking sample) by indenting with four spaces preceding the formatted line(s)
I'g the author of the volume "Implementing SSL/TLS Using Cryptography and PKI". Like the title says, this is a from-the-footing-up exam of the SSL protocol that provides security, integrity and privacy to most application-level internet protocols, about notably HTTP. I include the source lawmaking to a complete working SSL implementation, including the most popular cryptographic algorithms (DES, 3DES, RC4, AES, RSA, DSA, Diffie-Hellman, HMAC, MD5, SHA-1, SHA-256, and ECC), and evidence how they all fit together to provide transport-layer security.
Joshua Davies
Past Posts
- April 30, 2021: A Date Picker Command in Vanilla Javascript
- March 31, 2021: A Web Admin Console for Redis, Role Three
- January 27, 2021: A Web Admin Console for Redis, Part Two
- December 21, 2020: A Web Admin Console for Redis, Function 1
- November 30, 2020: What is Procmail and why is information technology using up all my memory?
- September 30, 2020: Minimal Drag and Driblet Support in Javascript
- Baronial 31, 2020: Covariance and Contravariance in Generic Types
- July 31, 2020: How Spread Out Are the Floating Bespeak Numbers?
- June 25, 2020: ERD Diagramming Tool, Role 3
- April 30, 2020: ERD Diagramming Tool, Part Two
- March 31, 2020: ERD Diagramming Tool, Part One
- February 28, 2020: MathJax and "t.setAttribute is not a role"
- Dec 30, 2019: Solving Systems of Equations with Python
- Oct thirty, 2019: Linear Regression with and without numpy
- September 30, 2019: Reading a Parquet file exterior of Spark
- Baronial thirty, 2019: UML Diagrams with MetaUML
- July 30, 2019: Clustering in Python
- June 25, 2019: A Walkthrough of a TLS ane.3 Handhsake
- May 31, 2019: A DataType Printer in Java
- April thirty, 2019: A Elementary HTTP Server in Java, Office 3 - Cookies and Keep Alives
- March 28, 2019: A Simple HTTP Server in Java, Office 2 - Mail and SSL
- Feb 28, 2019: A Simple HTTP Server in Java
- January 29, 2019: Athwart CLI Backside the Scenes, Part Two
- September 30, 2018: Angular CLI Behind the Scenes, Part One
- August 31, 2018: Into the MMIX MOR Education
- July 24, 2018: Undoing Pct Changes in your Head
- June thirty, 2018: Generating Langford Pairs in Scala
- May 25, 2018: Reflections on Three Years of Reading Knuth
- April 30, 2018: java.lang.NoSuchMethodError: org.junit.vintage. engine.descriptor.RunnerTestDescriptor. getAllDescendants
- March 30, 2018: An Excel Spreadsheet for the Academy Awards
- February 28, 2018: Git for Subversion Users
- January 31, 2018: The Evolution of AngularJS
- Dec 31, 2017: Numerical Integration in Python
- October 31, 2017: Gradle for Java Developers
- September 29, 2017: Reflections on another yr of reading Knuth
- Baronial 30, 2017: SSL OCSP Commutation
- July 27, 2017: A walk-through of an SSL certificate commutation
- June 30, 2017: A walk-through of an SSL key exchange
- May 31, 2017: A walk-through of the SSL handshake
- March 31, 2017: A walk-through of the TCP handshake
- February 28, 2017: The TLS Handshake at a High Level
- January 31, 2017: A Walk-through of a JWT Verification
- August 31, 2016: Reflections on a year of reading Knuth
- July 29, 2016: Matching a individual key to a public key
- June 30, 2016: A Completely Dissected GZIP File
- May 31, 2016: Automatic Guitar Tablature Generator, Part two
- April 28, 2016: Automatic Guitar Tablature Generator, Function i
- March 31, 2016: Import an encrypted private key into a Java Fundamental Store
- February 26, 2016: Import a individual primal into a Java Fundamental Shop
- Jan 31, 2016: Debian Linux on MacBook Pro
- December 29, 2015: Is Information science necessary or useful for programmers?
- November 30, 2015: Client certificate authentication vs. countersign authentication
- October 28, 2015: A Utility for Viewing Java Keystore Contents
- September 29, 2015: Debugging jQuery with Chrome'southward Developer Tools
- August 26, 2015: Getting Perl, MySQL and Apache to all piece of work together on Mac Bone/X
- July 30, 2015: Extract certificates from Coffee Cardinal Stores for use past Roll
- June 29, 2015: Using the Chrome web programmer tools, Part 9: The Console Tab
- May 28, 2015: Using the Chrome web developer tools, Part viii: The Audits Tab
- Apr 30, 2015: Using the Chrome web developer tools, Part 7: The Resources Tab
- March thirty, 2015: Using the Chrome web developer tools, Part 6: The Memory Profiler Tab
- February 27, 2015: Using the Chrome web developer tools, Function 5: The CPU Profiler Tab
- January 31, 2015: Using the Chrome spider web developer tools, Function 4: The Timeline Tab
- December 31, 2014: Using the Chrome spider web programmer tools, Part 3: The Sources Tab
- October 31, 2014: Using the Chrome web programmer tools, Office 2: The Network Tab
- September thirty, 2014: Using the Chrome web developer tools, Part i: The Elements Tab
- Baronial 11, 2014: Unable to detect valid certification path to requested target
- June 30, 2014: Sort by a Bureaucracy
- May 29, 2014: OpenSSL Tips and Tricks
- April 25, 2014: Heartbleed: What the Heck Happened
- February 28, 2014: Replace Microsoft Money with a Spreadsheet
- January 29, 2014: An Illustrated Guide to the Creature Attack
- Dec 21, 2013: Where does GCC look to discover its header files?
- October 24, 2013: Planning a Subversion import
- Baronial 28, 2013: Compile and exam an iOS app from the command line
- July 31, 2013: The Hidden Costs of Software Reuse
- June 26, 2013: Beware of mvn war:inplace
- May 29, 2013: Block Font Design Using Javascript
- April 4, 2013: Parsing a POM file using only SED
- February 22, 2013: Inside the PDF File Format
- Dec 31, 2012:How and why rotation matrices work
- November 27, 2012:Date Direction in Coffee
- October 21, 2012: Installing Debian Without a Network
- August 14, 2012: My Review of Matt Neuburg's "Programming iOS 5"
- July 16, 2012: An example OAuth i.0 Handshake and mini-library
- May 23, 2012: A Javascript 1-liner to display cookie values
- Apr 27, 2012: How SSL Certificates Use Digital Signatures
- March 29, 2012: A breakdown of a GIF decoder
- Feb fifteen, 2012: The pattern and implementation of LZW (the GIF compression algorithm)
- January 16, 2012: Calculate the day of week of any date... in your head
- December 4, 2011: Agreement CRC32
- October 29, 2011: Efficient Huffman Decoding
- October 4, 2011: Extract a private central from a Gnu Keyring file
- September 5, 2011: From Make to Ant to Maven
- July xviii, 2011: A lesser-upwardly await at the Apache configuration file
- July 6, 2011: Fun with the HTML 5 Canvas Tag
- Jun 16, 2011: Pain and disfiguration upon all comment spammers
- May 31, 2011: Use of RSSI and Time-of-Flight Wireless Point Characteristics for Location Tracking
- May 7, 2011: Implementing SSL
- Apr 24, 2011: Dissecting the GZIP format
Source: https://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art026
Postar um comentário for "How to Tell Clang to Read Include Directories"