0

I have several global critical sections that need visibility across 3 or more classes defined in 3 or more .cpp files. They're defined in an h file as:

GlobalCS.h

#pragma once
#include "stdafx.h"
extern CRITICAL_SECTION g_cs1;
extern CRITICAL_SECTION g_cs2;
etc...

In a GlobalCS.cpp they are defined

#include "stdafx.h"
#include "GlobalCS.h"
CRITICAL_SECTION g_cs1;
CRITICAL_SECTION g_cs2;

Then in the cpp for the classes they need to work in they're included as

#include "stdafx.h"
#include "GlobalCS.h"

The linker is complaining giving unresolved external in the files where the critical sections are being used. I didn't expect this since the variables are defined as extern. What am I doing wrong or how do I get around this?

error LNK2001: unresolved external symbol "struct _RTL_CRITICAL_SECTION g_CS_SymbolStrPlotAccess" (?g_CS_SymbolStrPlotAccess@@3U_RTL_CRITICAL_SECTION@@A)

Kara
  • 6,115
  • 16
  • 50
  • 57
brimaa
  • 169
  • 3
  • 11

2 Answers2

1

Not sure why you are getting the error. I tried the same thing in Visual Studio and in _tmain function I wrote the following:

int _tmain(int argc, _TCHAR* argv[])
{
    //::g_cs1;
    ZeroMemory(&g_cs1, sizeof(::g_cs1));

    return 0;
}

And it built with no issues whatsoever.

santahopar
  • 2,933
  • 2
  • 29
  • 50
0

Thank you all for your help. It always is helpful to have sanity checks. The issue was once again Visual Studio setup. Visual Studio will generate link errors if it doesn't like the way you have files added to your project. This is the second bug I've encountered that generated a link error based on the way the project was configured. If it's that important VS should either prevent you from modifying a project in a harmful way or provide a proper error message.

Anyway, the error is the same as this one:

LNK2019 Error under Visual Studio 2010

I had the GlobalCS.h and GlobalCS.cpp in the source directory. I prefer it this way because I find it makes finding files and code faster and in a large c++ project, just moving around the code base is a significant time waster. So much time could be saved writing c++ code if the IDE was designed to help find code faster. 2012 is A LOT better than 2010 so I'll give MSFT that but there could be a lot more features to that end (afterall VS has been around for almost 2 decades now)these types of persistent problems just get in the way of development. When I moved GlobalCS.h to the Header folder and cleaned the project and rebuilt, everything compiled as expected. The other similar error VS will throw at you is when the .h file is in the code directory (so #includes work) but not in the project. I got the same error messages when that happened and it took a good couple days to figure that one out. In a small project, it might not be as problematic but in big solution with multiple projects and dozens of files, it can be problematic.

Community
  • 1
  • 1
brimaa
  • 169
  • 3
  • 11