1
// file1.h
#pragma once
void public1();
// file1.cpp
#include "file1.h"
void privateFunc() {}
void public1() {}
// file2.h
#pragma once
void public2();
// file2.cpp
#include "file2.h"
void privateFunc() {}
void public2() {}
// main.cpp
#include <iostream>
#include "file1.h"
#include "file2.h"
int main()
{
    std::cout << "Hello World!\n";
}

So I have 2 functions in the 2 implementation files that have the same name and same parameters, but the implementation is different. Both are not included in their header file, so I assume they compiler can distinguish them. I think this is the problem.

How can I make function privateFunc() private to the implementation file without putting it in a class? That is, when another file includes "file1.h" or "file2.h", it should not know privateFunc() exists.

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
Huy Le
  • 1,439
  • 4
  • 19

1 Answers1

2

To make a function private, you must declare it as static. Otherwise that symbol will be made available to the linker for resolving across multiple sources.

static void privateFunc() {}

Alternatively, you can declare it in an unnamed namespace:

namespace
{
    void privateFunc() {}
}

You can read more about unnamed namespaces here.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • Ah I didn't know that specific meaning of static exists. "static" in this situation means "do not include into other file", is it correct? – Huy Le Jul 17 '20 at 04:11
  • 1
    It means the function has internal linkage. This means another object file cannot reference it. Read this: https://en.cppreference.com/w/cpp/language/storage_duration – paddy Jul 17 '20 at 04:15