BinaryMonkey
BinaryMonkey

Reputation: 351

Understanding how a template function (with source in .h) relates to its compiled .lib

Suppose I want to send a C++ class (without source) to my friend Bob. I would send him a compiled .lib and the given MyClass.h:

class MyClass {
  public:
    /// Public template function for safety of size, implementation in .h
    template <class T>
    static int SendData(const T& data) {
        return SendDataUnsafe(&data, sizeof(T));
    };

  private:
    /// Private function with risky size, code implementation in .cpp and compiled in .lib
    static int SendDataUnsafe(PCVOID data, size_t data_size);
};

I understand that the source code of SendDataUnsafe in MyClass.cpp was compiled and partially linked into a MyClass64.lib (example). Since it is private, the Bob's compiler won't let him call SendDataUnsafe directly (unresolved external). So Bob must use the templated SendData instead. But I have some questions:

  1. Is there anything compiled about the SendData template into the .lib, since the implementation is entirely in the .h?

  2. Could Bob change the source code of SendData (in the .h) and replace sizeof(T) by something else to gain indirect access to SendDataUnsafe?

EDIT: If Bob removes the private: statement and tries to call SendDataUnsafe, he gets an ERROR (which seems in contradiction to comments received so far):

ERROR, LNK2019, unresolved external symbol "public: static int MyClass::SendDataUnsafe(void const *,unsigned __int64)" (...) referenced in function main

Upvotes: 1

Views: 64

Answers (1)

Captain Giraffe
Captain Giraffe

Reputation: 14705

Bob can absolutely call your private function. private is a compile-time compiler enforced restriction. I'm guessing if Bob were to remove the private: line from your header, his code would link fine. (now tested)

  1. No, the compiler can't generate any meaningful code for SendData.

  2. SendDataUnsafe is very visible in your .lib. You can't hide it in any meaningful way.

https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling Seems to support the conclusion that the mangled name does not include any mention of a private member.

Bob can also add a new function to your .h file and call the private member however he likes.

Upvotes: 1

Related Questions