Pressacco
Pressacco

Reputation: 2875

Should you: #import or "add new reference"?

In the past I would have used #import to gain access to functions exposed by a dynamically linked library (i.e. *.DLL). Now it appears that Visual Studio has a new Add New Reference option.

Project => Property Pages => Common Properties => References

My question is: which approach should I use?

REFERENCES

The following approach was used to expose functions in our library:

UPDATE 1

One thing I noticed is that: unlike in C# where you can add a reference to (1) an assembly in the GAC, (2) an assembly on the file system, (3) a project within the solution. It appears that in C++ you can only Add Reference to a project within the current solution.

Upvotes: 2

Views: 822

Answers (2)

Hans Passant
Hans Passant

Reputation: 942000

The specific rules:

  • #import should only be used on COM type libraries. Either the .tlb file or the .dll/.ocx if the type library is embedded in the executable file, very common. The compiler translates the type library to a .tli and a .tlh file that contain the declarations in a format that the compiler understands as well as smart pointer types and wrapper functions that make it a lot easier to deal with memory management and runtime errors. In C# you'd use Add Reference or Tlbimp.exe to do the same thing.

  • Add New Reference was meant for .NET assemblies in C++/CLI projects. The compiler imports the type declarations stored in the metadata of the assembly, the rough equivalent of a #including the .h file for a native DLL. And the exact equivalent of Add Reference in a C# project.

  • #include is used to include a .h file with declarations, the normal way to tell the C++ compiler about code that lives elsewhere.

  • Starting in VS2012, Add New Reference can now also be used to generate a link instruction for a static library or DLL project that's part of the solution. The linker simply gets the instruction to link the .lib file of the project. No equivalent for that in C#, it does not use a linker.

  • Project + Properties > Linker > Input > Additional Dependencies is the other way to do the same thing as the previous bullet. And must be used if the .lib file is not generated by a project in the solution.

Note the distinction between the two sets of bullets. The first 3 affect the compiler and are used to tell it about type declarations. The latter 2 affect the linker and are used to tell it to link code stored elsewhere.

Upvotes: 5

laurisvr
laurisvr

Reputation: 2822

Well I've had the same dilemma. I personally prefer import. That visualizes your approach a bit better I feel. But the main reason is that that way you can just export a header file. Without it breaking because of missing lib files.

But all and all it's a pretty much a matter of personal preference I reckon.

Upvotes: 0

Related Questions