简体   繁体   中英

Conflict of include files from an Arduino library

I'm writing Arduino libraries and have the folder structure as follows:

libraries   
  +Foo
    -Foo.h
    -Helper.h   
  +Bar
    -Bar.h
    -Helper.h   
  +Helper
    -Helper.h

Foo and Bar are the libraries I created. The reasoning behind putting Helper.h in their folders is that, end user will have an easier time getting the libraries to work. Also, some libraries can only be configured by having their source code edited.

However, if I write #include <Helper.h> in my sketch , it'll be impossible to control which "Helper.h" I'm including.

Is there a way to hide Helper.h from Foo and Bar from sketches?

The obvious answer is: don't write #include <Helper.h> . Your files aren't part of the implementation, and should be included using #include "Helper.h" . If you do this, the first place the compiler will look for the include file is in the directory containing the file which is including it: if you include it from Foo/Foo.h , the compiler will pick up Foo/Helper.h ; if you include it from Bar/Bar.h , the compiler will pick up Bar/Helper' and so on.

Client code should only set the include path to the root, and do things like #include "Foo/Foo.h" ; if necessary, they can also do #include "Foo/Helper.h" .

The one thing you do have to do with this strategy is to ensure the uniqueness of all of the header guards. If this is an application, it will usually be sufficient to mangle the path into the include guard, eg use Foo_Helper_h , instead of just Foo_h . Alternatively (and I would use this for any library which third parties should use), generate some random string for the include guard. (If I open a file named abc.h which doesn't exist, my editor automatically generates the following boilerplate:

/********************************************************/
/*      File:       abc.h                               */
/*      Author:     J. Kanze                            */
/*      Date:       02/05/2013                          */
/* ---------------------------------------------------- */

#ifndef abc_h_20130502O481MBxFZeAzz4dgIb7iC4Q9
#define abc_h_20130502O481MBxFZeAzz4dgIb7iC4Q9

#endif

It's a safe bet that the include guard here will never conflict with any other. (And you have to do something along these lines anyway, in order to get your copyright message in the file.)

Just figured out a way that seemingly solves the problem:

libraries   
  +Foo
    -Foo.h
    +extra
      -Helper.h   
  +Bar
    -Bar.h
    +extra
      -Helper.h   
  +Helper
    -Helper.h

In this way, Helper.h in Foo and Bar would be invisible to clients, and I can write #include "extra/Helper.h" in Foo and Bar respectively to include the desired files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM