Can the gcc static linker properly inline functions from a static library? - objective-c

If we compile a number of source codes which makes uses of a static library named lib.a, would the inline functions in lib.a get properly inlined with the rest of binaries?

no, they would not. Inlining is an operation on the parse tree and requires access to the source code for both the host and donor sources of the inlined code.
Static libraries have already been compiled from source to binary at the point you use them, so inlining cannot happen.
However, code that is not inlined is also 'proper' and will function just fine (assuming it got compiled into the static library at all).

Well, since in order to even attempt to call an inline function its declaration must be visible at the call site. If it is then inline then the compiler will either inline it or completely ignore the request.
If you are wondering if functions NOT declared inline that were inlined in the library can then also be inlined when you link to the final product...this would depend on the implementation and, assuming it is already capable of LTO (since it did it to the library), it very well might be able to inline them again. You may be required to cause the implementation to include the definition even when it's been inlined everywhere though...all depends on the implementation.
http://crazyeddiecpp.blogspot.com/2010/12/inline-functions-and-you.html

Related

Inline function versus macro

I'm working on an iOS app using C and Objective-C, and I want to write a very small piece of code that will be executed thousands of times from more than one place. Is it safe to make this an inline function and be sure that it will always be expanded (I won't ever be taking its address) or should I make it a macro? The code is small and it will be executed very frequently, so I'd like to make sure I won't end up with thousands of function calls for it, but still I'd like the type safety of the function approach if possible...
If you want to be sure that a function is inlined, make it "extern inline" (this is a GNU-C feature). Such functions are only used for inlining; the compiler will never generate a "real" function for it. Thus, if the inlining fails, you should be getting linker errors. I assume clang has "inherited" this feature.
In general, always use inline instead of macros, if possible. There's a reason why many C-compilers had it for ages, and C++ finally added it as a core feature; it makes things a lot safer and reliable to use. There are still things that need macros, but those are few and far between.
Yes, you should use an inline function over a macro.
The performance will be identical to a macro (the code is inline, after all) and you'll get type safety as well.
N.B., this assumes that your function is simple enough for the compiler to inline. gcc's -Winline option warns if this isn't the case; not sure what flags do the same on your platform.
Also see this post for cases when you might prefer a macro (e.g., deferred evaluation)--but based on your question it sounds like inline function is the clear choice.
I may be wrong, but I understand a compiler can only inline functions which are in the same source file. If your inline function is in file A and you're trying to use it elsewhere, it cannot be inlined, unless the linker does link-time optimization.
This is because the compiler only compiles one C file at a time into one object file. It cannot obtain the inlined function from another object file, because firstly, it may not yet have been compiled and secondly, it wouldn't know which object file to look for anyway.

Static, extern and inline in Objective-C

What do static, extern and inline (and their combinations) mean in Objetive-C using the LLVM compiler?
Also, I noticed that there are CG_EXTERN and CG_INLINE macros. Should we be using those instead?
(I couldn't find a source with a clear explanation so I thought it might be useful to create one here, or point to it if someone knows one)
What do static, extern and inline (and their combinations) mean in Objetive-C using the LLVM compiler?
The same as in C, unless you compile as ObjC++ -- then they mean the same as found in C++.
So here is an introduction for C, but read the links if you are ready to use these because the details are important:
Extern
Summary: Indicates that an identifier is defined elsewhere.
Details: http://tigcc.ticalc.org/doc/keywords.html#extern
Static
Summary (value): Preserves variable value to survive after its scope ends.
Summary (function): Effectively emits unnamed copies - useful for private functions in C, and can be used to escape multiple definition errors when used with inline functions.
Details: http://tigcc.ticalc.org/doc/keywords.html#static
Inline
Summary: Suggests the body of a function should be moved into the callers.
Details: http://tigcc.ticalc.org/doc/gnuexts.html#SEC93
Note that inline and static are quite a bit more complex in C++ (like pretty much everything in C++).
I also found that there are CG_EXTERN and CG_INLINE macros. Should we be using those instead?
No.
Instead, you should specify your own, with your own meanings, if you need this type of functionality. CG_EXTERN and CG_INLINE have specific meanings (which may change), and are meant to be used in their defined context -- also, you don't want to have to include a whole handful of frameworks (all CoreGraphics/ApplicationServices/CoreFoundation/etc.) when you want to specify something is extern in a way that works in C and C++.
Justin covered most of it, but I found some other nice resources for those who want to dig deeper:
By declaring a function inline you tell the compiler to replace the complete code of that function directly into the place from where it was called. This is a rather advanced feature that requires understanding of lower-level programming.
Inline functions
This SO question has an enormous answer about extern variables - variables defined "somewhere else" - but need to be used also "here".
Static preserves variable life outside of scope. The Variable is visible within the scope it was declared.
What does a static variable mean?

Is there anything in the C++0x standard to support separate compilation of templates?

In current g++, I typically include all my templated functions that take the template parameter as an argument because they have to be compiled for each instance.
template<typename T>
class A {
public:
void f() { ... }
};
So in a different source, I would write:
#include <A.hh>
A<int> a1;
a1.f();
A<double> a2;
a2.f();
Sometimes, when I've been desperate to not inline big methods, I've manually specified which classes will be used in the source file, but it's really obnoxious:
template<typename T>
A::A() { ... }
template<typename T>
void A::f() { ... }
A<int>; // manually trigger code generation for int and double
A<double>;
Obviously different IDEs and compilers have mechanisms to support this. Is there anything standard that has been mandated, and/or does g++ support anything like this?
There's nothing in the proposed C++0x standard. In fact, export template has been removed (few compilers implemented it anyway).
As far as inlining is concerned, it's a total non-issue. The compiler is smart enough not to inline functions which are too big, even if they're marked inline and put into a header file.
If you're looking at increased compile times from header files grown bloated from templates, use precompiled headers. These aren't standard, but almost all current compilers provide such a mechanism.
C++0x does have extern template, which allows you to prevent the instantiation of certain templates in a compilation unit. So if you have a template class SomeClass, you can put this in the header:
extern template SomeClass<int>;
extern template SomeClass<double>;
This will prevent users from instantiating the template. In the .cpp file for the template, you can force instantiation with this syntax:
template SomeClass<int>;
template SomeClass<double>;
I've manually specified which classes will be used in the source file, but it's really obnoxious:
A<int>; // manually trigger code generation for int and double
A<double>;
This is not legal (I assume you meant to declare dummy variables here, and missed their name). We will see below why
Is there anything standard that has been mandated, and/or does g++ support anything like this?
C++03 had something called export, but which turned out to be a misfeature. The EDG implemented that feature, and their experience with it indicated that it's not worth the trouble implementing it. And it doesn't provide a useful feature separate compilation usually gives you: Hiding of the code of templates which you once compiled. export still requires the code of templates, be it in raw form or encoded into a mid-level compiler-specific language. See Why we can't afford export. A short example is given by EDG worker David Vandevoorde here.
For C++0x and for C++0x sans export, we have
A function template, member function of a class template, or static data member of a class template shall be defined in every translation unit in which it is implicitly instantiated (14.7.1) unless the corresponding specialization is explicitly instantiated (14.7.2) in some translation unit; no diagnostic is required
As this indicates, the only way you can achieve separate compilation is to explicitly instantiate the template you want to have separately compiled. By defining dummy variables, you merely implicitly instantiate the class template. And you do not instantiate the member functions of the class templates that way - you would need to do dummy calls or take their address. And to all this, you are not guaranteed that an implicitly instantiated function won't be discarded if it's not used in the translation unit it was instantiated by, after optimization, based on the above quote.
So you explicitly instantiate the class template, which will explicitly also instantiate its member functions the following way:
template class A<int>;
template class A<double>;
This feature, called export is present even in the current standard of C++. Unfortunately, most compilers, including gcc, do not support it. See here http://gcc.gnu.org/bugs/

How can I force GCC to compile functions that are not used?

I am splitting off some of the code in my project into a separate library to be reused in another application. This new library has various functions defined but not implemented, and both my current project and the other application will implement their own versions of these functions.
I implemented these functions in my original project, but they are not called anywhere inside it. They are only called by this new library. As a result, the compiler optimizes them away, and I get linking failures. When I add a dummy call to these functions, the linking failures disappear.
Is there any way to tell GCC to compile these functions even if they're not being called?
I am compiling with gcc 4.2.2 using -O2 on SuSE linux (x86-64_linux_2.6.5_ImageSLES9SP3-3).
You could try __attribute__ ((used)) - see Declaring Attributes of Functions in the gcc manual.
Being a pragmatist, I would just put:
// Hopefully not a name collision :-)
void *xyzzy_plugh_zorkmid_3141592653589_2718281828459[] = {
&functionToForceIn,
&anotherFunction
};
at the file level of one of your source files (or even a brand new source file, something along the lines of forcedCompiledFunctions.c, so that it's obvious what it's for).
Because this is non-static, the compiler won't be able to take a chance that you won't need it elsewhere, so should compile it in.
Your question lacks a few details but I'll give it a shot...
GCC generally removes functions in very few cases:
If they are declared static
In some cases (like when using -fno-implement-inlines) if they are declared inline
Any others I missed
I suggest using 'nm' to see what symbols are actually exported in the resulting .o files to verify this is actually the issue, and then see about any stray 'static' keywords. Not necessarily in this order...
EDIT:
BTW, with the -Wall or -Wunused-function options GCC will warn about unused functions, which will then be prime targets for removal when optimising. Watch out for
warning: ‘xxx’ defined but not used
in your compile logs.
Be careful as the -Wunused-functions doesn't warn of unused functions as stated above. It warns of ununsed STATIC functions.
Here's what the man page for gcc says:
-Wunused-function
Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is
enabled by -Wall.
This would have been more appropriate as a comment but I can't comment on answers yet.

Converting c++ project to clr safe project

I need to work on converting a very huge c++ project to clr safe. The current c++ project has a lot of stuff from c++ like templates, generics, pointers, storage/stream, ole apis, zlib compression apis, inlines etc. Where can I find the datiled document for this type of conversion? Can you suggest some good book to refer to? If anyone of you have done such conversion, can I get some analysis from you?
I'll just cough up the MSDN Library article titled "How to: Migrate to /clr:safe
Visual C++ can generate verifiable components with using /clr:safe, which causes the compiler to generate errors for each non-verifiable code construct.
The following issues generate verifiability errors:
Native types. Even if it isn't used, the declaration of native classes, structures, pointers, or arrays will prevent compilation.
Global variables
Function calls into any unmanaged library, including common language runtime function calls
A verifiable function cannot contain a static_cast Operator for down-casting. The static_cast operator can be used for casting between primitive types, but for down-casting, safe_cast or a C-Style cast (which is implemented as a safe_cast) must be used.
A verifiable function cannot contain a reinterpret_cast operator (or any C-style cast equivalent).
A verifiable function cannot perform arithmetic on an interior_ptr. It may only assign to it and dereference it.
A verifiable function can only throw or catch pointers to reference types, so value types must be boxed before throwing.
A verifiable function can only call verifiable functions (such that calls to the common language runtime are not allowed, include AtEntry/AtExit, and so global constructors are disallowed).
A verifiable class cannot use Explicit.
If building an EXE, a main function cannot declare any parameters, so GetCommandLineArgs must be used to retrieve command-line arguments.
Making a non-virtual call to a virtual function.
Also, the following keywords cannot be used in verifiable code:
unmanaged and pack pragmas
naked and align __declspec modifiers
__asm
__based
__try and __except
I reckon that will keep you busy for a while. There is no magic wand to wave to turn native C++ into verifiable code. Are you sure this is worth the investment?
The vast majority of native C++ is entirely valid C++/CLI, including templates, inlines, etc, except the CLR STL is rather slow compared to the BCL. Also, native C++ doesn't have generics, only templates.
The reality of compiling as C++/CLI is to check the switch and push compile, and wait for it to throw errors.
Rewriting native C++ into safe C++/CLI will result in a code that is syntactically different, but semantically same as C#. If that is the case, why not rewrite directly in C#?
If you want to avoid what is essentially a complete rewrite, consider the following alternatives:
P/Invoke. Unfortunately, I'm unfamiliar whether this would isolate safe from unsafe code. Even if it can perform the isolation, you'll need to wrap your existing C++ code into procedural, C-like API, so it can be consumed by P/Invoke. On a plus side, unless your API is excessively chatty, you get to keep (most of) your native performance.
Wrapping your C++ into out-of-process COM server and using COM Interop to consume it from the manged code. This way, your managed code is completely protected from any corruption that might happen at C++ end and can remain "safe". The downside is a performance hit that you'll get for out-of-process marshaling and the implementation effort you'll need to expend to correctly implement the COM.