1

Using C and plain functions in C++, I can prevent the functions' symbols to be exported by using static keyword:

static int foo(int a, int b) { /* ...  */ }

But in a class, defining a function as static has a completely different meaning. Is there a way to ensure the compiler that my whole class will be used only within module, and there is no need to export any of its methods' symbols?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
lvella
  • 12,754
  • 11
  • 54
  • 106

3 Answers3

7

Use an anonymous namespace.

namespace
{
    class C
    {
        C() {}
        void f() {}
    };

    void f();
}

class ExportedClass
{
    ExportedClass() {}
    void f() {}
};

void exportedFunction() {}

As you can see, you should do this for normal functions, too. The usage of static for this is discouraged.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
5

You can use the anonymous namespace. For example,

// file foo.cc
namespace {
    int symbol1 = 0;
    struct auxiliary { /* ... */ } symbol2;
}

void foo(int x)
{
  // uses symbol1 and symbol2
}

when symbol1 and symbol2 are not 'visible'.

Walter
  • 44,150
  • 20
  • 113
  • 196
-4

Depending on what you want and why you are doing it you could move the class into the .cpp file. This works for example if you are implementing a library. Have a look at the discussion at Putting class declaration in .cpp file

To be more specific your class should go in it's own separate translation unit away from main and away from classes outside of your module.

Community
  • 1
  • 1
london-deveoper
  • 533
  • 3
  • 8
  • My class declaration is already in a `.cpp`, but AFIK, that doesn't change compiled symbol visibility (headers inclusions are preprocessed, so the compiler can't really know if the class definition was originally in a `.hpp` header or not). I believe your answer is wrong. – lvella Jan 24 '17 at 19:33
  • class definitions will only be visible in the cpp module so unless you include the cpp file in another translation unit then the symbols will not be visible. see http://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c – london-deveoper Jan 24 '17 at 19:41
  • 1
    That's only true at the compiler level, but not on the linker level, where identically named symbols in different translation units can violate the ODR. – Christian Hackl Jan 24 '17 at 19:46
  • If you were supplying a dynamic library for example I don't think that would be an issue. For a static linkage I guess so. My statements made too many assumptions. I didn't think it though fully and I moved from focus from avoid export to avoiding usage. My mistake. Thanks for your comments. – london-deveoper Jan 24 '17 at 20:02