Search code examples
c++clangforward-declaration

Fixing circular dependencies c++17 headers


I am using a clang C++17 compiler and I am getting the warning:

declaration of 'struct Xchart' will not be visible outside of this function. 

This warning is pointing to a function declaration that uses a structure that is declared in a different header file. I believe this is caused by circular dependencies in the two header files but I have not been able to resolve the warning

Header toolkit.h declares the function MyFunction which uses the structure Xchart as an input. This is where the warning points.

toolkit.h

#ifndef _TOOLKIT_H
#define _TOOLKIT_H 1

#define _WINDOWS 1
#include <windows.h>

short WINAPI MyFunction(struct Xchart *mychart ); <--Warning Here

#pragma pack(push, 1)
#pragma pack(pop)
#endif /*_TOOLTKIT_H */

Header mystruct.h declares the Xchart structure

mystruct.h

#ifndef _mystructs_h
#define _mystructs_h 1

#include "toolkit.h"

#pragma pack(push, 1)

struct Xchart { 
  int MyDays;   
  short LoadMe;   
  wchar_t MyLabel[100]; 
};

#pragma pack(pop)
#endif /* _mystructs_h */

Can you show how to change these two header files so the warning is resolved?


Solution

  • The usual fix is simple:

    struct Xchart; // declares Xchart; definition is elsewhere.
    short WINAPI MyFunction(Xchart *mychart); // Function declaration.
    

    Only toolkit.cpp will need the definition of Xchart, but .cpp files themselves are not included elsewhere and don't contribute to circular inclusions.