Repository navigation
Description
This issue was originally created at: 2008-11-01 23:58:39.
This issue was reported by: jchristian.
jchristian said at 2008-11-01 23:58:39
Scons Version: Using "vs_revamp" branch build off of the 1.1.0 release. I suspect this problem happens on the official 1.1.0 release, but I haven't checked it.
Compiler: VS2008
Defect Summary: In attempting to use precompiled headers in building a Windows project, I ran into a fairly obscure bug. Apparently, if the filename specified as the source file for the PCH generation begins with the letter 'c' or 'C', the build regenerates the PCH file every time the build is run...even if no files have changed. If I change that filename to begin with another letter, it works. Note that originally my PCH source file was called "CorePCH.cpp". In trying things, I found it could be shortened to just "C.cpp" and produce the problem.
Expected Behavior: On the second build, it should just return with an "up to date" status.
Below is my directory structure and the files needed to reproduce the issue. Note that once you get this all setup, you can make it work successfully by changing the filename C.cpp in the SConscript to just PCH.cpp or XCorePCH.cpp.
Let me know if you have questions.
Directory structure:
project
|
+--SConstruct
|
+--include
| |
| +-- core
| |
| +-- CorePCH.hpp
| Hello.hpp
|
+-- lib
|
+-- core
|
+-- CorePCH.cpp
Hello.cpp
SConscript
SConscript:
import glob
# get all the build variables we need
Import("env", "buildroot", "project", "mode", "debugcflags", "releasecflags")
staticlibenv = env.Clone()
builddir = buildroot + "/" + project # holds the build directory for this
project
targetpath = builddir # holds the path to the executable in the build directory
# append the user's additional compile flags
# assume debugcflags and releasecflags are defined
if mode == "debug":
staticlibenv.Append(CPPFLAGS=debugcflags)
else:
staticlibenv.Append(CPPFLAGS=releasecflags)
# get source file list
srclst = map(lambda x: builddir + "/static/" + x, glob.glob("*.cpp"))
# specify the build directory
staticlibenv.BuildDir(builddir + "/static", ".", duplicate=0)
staticlibenv2 = staticlibenv.Clone()
staticlibenv2["PCHSTOP"] = "core/CorePCH.hpp"
# pch.cpp is beside this SConscript
staticlibenv2["PCH"] = staticlibenv2.PCH(builddir + "/static/C.cpp")[0]
print("here 0")
print(staticlibenv2["PCH"])
print("here 1")
additionalcflags = ["-Yl__xge_pch_symbol"]
staticlibenv2.Append(CPPFLAGS=additionalcflags)
staticlib = staticlibenv2.StaticLibrary(targetpath + "/static/core", source=srclst)SConstruct:
# get the mode flag from the command line
# default to 'release' if the user didn't specify
mode = ARGUMENTS.get("mode", "debug") # holds current mode
platform = ARGUMENTS.get("platform", "win32") # holds current platform
# check if the user has been naughty: only 'debug' or 'release' allowed
if not (mode in ["debug", "release"]):
print("Error: expected 'debug' or 'release', found: " + mymode)
Exit(1)
# check if the user has been naughty: only 'win32' or 'xbox' allowed
if not (platform in ["win32", "xbox"]):
print("Error: expected 'win32' or 'release', found: " + platform)
Exit(1)
# tell the user what we're doing
print("**** Compiling in " + mode + " mode...")
debugcflags = [ # extra compile flags for debug
"-Od",
"-MDd",
"-Ob0",
"-Z7",
"-W4",
"-EHsc",
"-GR",
"-D_DEBUG",
"-DUSE_PCH",
]
releasecflags = [ # extra compile flags for release
"-O2",
"-MD",
"-Ob2",
"-EHsc",
"-GR",
"-DNDEBUG",
"-DUSE_PCH",
]
env = Environment()
env.Append(CPPPATH=["#include", "#ext/boost-1.34.1"])
if mode == "debug":
env.Append(LINKFLAGS="/DEBUG")
buildroot = "#build/" + mode # holds the root of the build directory tree
# make sure the sconscripts can get to the variables
Export("env", "mode", "platform", "debugcflags", "releasecflags")
# put all .sconsign files in one place
env.SConsignFile()
# specify the sconscript for myprogram
project = "lib/core"
SConscript(project + "/SConscript", exports=["buildroot", "project"])CorePCH.hpp:
#ifndef CORE_PCH_HPP
#define CORE_PCH_HPP
#ifdef USE_PCH
#include <string>
#include <iostream>
#include "core/Hello.hpp"
#endif
#endif // CORE_PCH_HPPCorePCH.cpp or C.cpp:
#include "core/CorePCH.hpp"Hello.hpp:
#ifndef HELLO_HPP
#define HELLO_HPP
#ifndef USE_PCH
#include <string>
#endif
class Hello
{
public:
Hello(const std::string& msg);
~Hello();
void sayIt();
private:
std::string m_msg;
};
#endif // HELLO_HPPHello.cpp:
#include "core/CorePCH.hpp"
#ifndef USE_PCH
#include "core/Hello.hpp"
#include <iostream>
#endif
Hello::Hello(const std::string& msg):m_msg(msg)
{
}
Hello::~Hello()
{
}
void Hello::sayIt()
{
std::cout << m_msg << std::endl;
}jchristian said at 2008-11-02 00:08:53
I made this a P2 because even though it is obscure, it is hella hard to track down what is going on. The workaround is to simply use another filename but this isn't apparent until many hours have been wasted. As well, I suspect the fix will be trivial and from my experience P3 and P4 defects tend to get put off practically forever.
jchristian said at 2008-11-04 00:39:53
Created an attachment (id=531)
Zip file that creates the dir structure described in the defect
jchristian said at 2008-11-04 00:49:32
Upon further investigation I have found that the filenames A.cpp thru H.cpp do not work. I have confirmed that I.cpp thru Q.cpp work. And also X.cpp. Other filenames were not tested because I got tired of doing it. To test a different filename, simply rename C.cpp in the lib/core directory and then update the SConscript file in that same directory to use that filename.
My suspicion is that the dependencies are not being generated or kept because of some defect in parsing or concatenating the filename.
jchristian said at 2008-11-04 00:55:43
Hopefully this can be fixed for 1.2
gregnoel said at 2008-12-04 17:41:09
1.2 is frozen; issues that didn't make it into 1.2 are moved to 1.3.
stevenknight said at 2008-12-06 11:22:53
This issue erroneously had a target milestone put on it right away, so it never got discussed and assigned to someone specific. Consequently, it's been languishing in a 1.[23] + issues@scons bucket that no one actually looks at. Change the target milestone to -unspecified- so we can discuss this at the next Bug Party and get it prioritized appropriately.
gregnoel said at 2008-12-24 06:41:53
Bug party triage. Steven suggests that it might be an interaction with the heuristics for determining the drive letter, but otherwise nobody has a clue. Assign to Steven for research as a penalty for suggesting a possibility.
Next time let us assign the milestone and priority. If it doesn't pass through our process, it'll get lost as this one did.
jchristian said at 2008-12-24 12:26:00
Sorry about that, I'll do that in the future. This was my first issue submitted and I wasn't sure what to put on some of the fields :O
stevenknight said at 2009-11-10 18:00:19
stevenknight => issues@scons
gregnoel said at 2010-01-20 02:20:51
Bug party triage. This area has been heavily revamped. Bill to research and see if the problem still happens.
John, can you try your test case with the newest checkpoint (published yesterday) and see if it's been fixed? Add a note to this issue and let us (well, Bill, to be precise) if you still see the problem. Tks.
gregnoel said at 2010-07-21 16:58:11
Bug party triage. Bump this issue to P1 so it will be reviewed at next bug party.
jchristian attached testpch.zip at 2008-11-04 00:39:53.
Zip file that creates the dir structure described in the defect
Activity
mwichmann commentedon Apr 7, 2021
Tagged this with variantdir because that (in the old form BuildDir) appears in the SConscript.
mwichmann commentedon Nov 3, 2023
Something about this sounds familiar - wasn't there some ordering issue? #2877 has one of these.
bdbaddog commentedon Nov 4, 2023
The original filer is using
glob.glob('*.cpp')which doesn't guarantee order staying the same between runs... That could have something to do with this..bdbaddog commentedon Nov 4, 2023
The original filer is using
glob.glob('*.cpp')which doesn't guarantee order staying the same between runs... That could have something to do with this..I've imported the zip file and updated for python3 and BuildDir->VariantDir change.
Here: https://github.com/bdbaddog/scons-bugswork/tree/main/2249
This also has the problem where the VariantDir()'s source is a parent of the variantdir..
staticlibenv.VariantDir(builddir+"/static", ".", duplicate=0)With my updates and one more, it's not finding c.pch in static.
bdbaddog commentedon Nov 4, 2023
Not exactly sure what's the issue.
Here's the generated command line which get's run (after my changes.. I moved variant_dir to the SConscript call so the variantdir wasn't a child of the src dir).
When it gets run, it doesn't generated any files? (@jcbrill - any idea? I'm not the PCH expert by far)..
cl /Fobuild\debug\lib\core\static\C.obj /c build\debug\lib\core\static\C.cpp /TP /nologo -Od -MDd -Ob0 -Z7 -W4 -EHsc -GR -D_DEBUG -DUSE_PCH -Yl__xge_pch_symbol /Iinclude /Yucore/CorePCH.hpp /Fpbuild\debug\lib\core\static\C.pchAll my updates are available here: https://github.com/bdbaddog/scons-bugswork/tree/main/2249
jcbrill commentedon Nov 4, 2023
I'm not either. When proceeding, keep in mind I'm just trying to help.
The sample files do illustrate a problem though.
There does appear to be a lexical ordering issue.
Using a recent version of scons with the build files, I had to change one line in the
SConscriptfile due to a "PCHSTOP construction variable must be a string" error.Original:
Modified:
Working thesis: Any generated pch file name that is lexically ordered before "core" fails while any generated pch file name that is lexically ordered after "core" passes.
File
C.cpp(C.pch) is lexically ordered before core and fails.File
Z.cpp(Z.pch) is lexically ordered after core and passes.The results from two builds with and environment dump and command-line options
--taskmastertrace - --tree=allare included in the text filescorD-fail.txt(source filecorD.cpp) andcorF-pass.txt. (source filecorF.cpp).corD-fail.txt
corF-pass.txt
File
corD-fail.txtcontains the results when usingcorD.cppfor the file name (pch_nodes = staticlibenv2.PCH("corD.cpp"))File
corF-fail.txtcontains the results when usingcorF.cppfor the file name (pch_nodes = staticlibenv2.PCH("corF.cpp"))corD-fail.txtThe tree for
corD-fail.txtis:corF-pass.txtThe tree for
corF-pass.txtis:Hope this points someone in the right direction.
Edit: Does the lexical ordering issue indicate a potential dependency issue?
36 remaining items
jcbrill commentedon Nov 7, 2023
Old but useful: https://stackoverflow.com/questions/35408988/lnk2011-why-does-link-exe-require-stub-obj-to-be-linked-alongside-precompiled-h
I'm starting to wonder if there could be a problem when linking with created static library in another program since the pch object file is not included when building the static library. Any thoughts?
I tested the modified example above to generate a SharedLibrary and it does in fact include the pch object file when linking.
jcbrill commentedon Nov 8, 2023
@mwichmann and @bdbaddog PCH generation issue and possible code change solution explained.
Description of terms used below:
The mermaid diagrams are rendered when viewing the GitHub html page.
Observed Behavior
From above in this thread:
PCH source file rebuilt every time when certain filenames are used #2249 (comment)
PCH source file rebuilt every time when certain filenames are used #2249 (comment)
There is an issue when both the environment PCH method is called and the pch source file is included in the source file list that can result in build failure.
Summary:
The reason why the build may succeed in some configurations and fail in other configurations when the pch source file is in the source list is described in the next section.
Issue Description and Illustration
When both the environment PCH method is called and the pch source file is included in the source file list, the PCH.obj node has two builders/emitters assigned during construction with the second builder/emitter overwriting the original builder/emitter.
This is undesirable as a taskmaster evaluation criteria has been removed and the lexical ordering of nodes affects the evaluation order during the DAG walk. The DAG walk and evaluation order is not deterministic. Builds that are successful, succeed for the wrong reason.
SConscript fragment that results in State A and State B in the diagrams below (some build configurations may fail):
SConscript fragment that results in State A, State B, and State C in the diagrams below (all build configurations pass):
The second call to the environment PCH method resolves the issue and is presented for exposition purposes only. However, the behavior informs the proposed solution below.
Node PCH.pch and PCH.obj states:
State A: env.PCH('PCH.cpp')
flowchart LR subgraph 1 ["State A: env.PCH('PCH.cpp') => msvc.pch_emitter"] direction LR N1[PCH.pch] --> B1["Builder $PCHCOMSTR"] --> E1["Executor $CXX ... <br> target=[PCH.pch, PCH.obj], source=[PCH.cpp]"] N2[PCH.obj] --> B1 endThe environment PCH method causes the pch emitter to be assigned to both the PCH.pch and PCH.obj nodes.
The first target for the PCH.pch and PCH.obj nodes is PCH.pch (e.g., target[0]==PCH.pch).
State B: StaticLibrary('core', source=['PCH.cpp', 'Hello.cpp'])
flowchart LR subgraph 2 ["State B: StaticLibrary('core', source=['PCH.cpp', 'Hello.cpp']) => msvc.static_object_emitter"] direction LR N3[PCH.pch] --> B2["Builder $PCHCOMSTR"] --> E2["Executor $CXX ... <br> target=[PCH.pch, PCH.obj], source=[PCH.cpp]"] N4[PCH.obj] --> B3["Builder CXXAction"] --> E3["Executor $CXX ... <br> target=[PCH.OBJ], source=[PCH.cpp]"] endThe environment StaticLibrary method causes the static object emitter to be assigned to the PCH.obj node.
The first target for the PCH.obj node is now PCH.obj (e.g., target[0]==PCH.obj) and not PCH.pch.
The target[0] change influences the DAG walk evaluation order and is the root cause of the build failures. However, even in the builds that succeed, they are really succeeding for the wrong reason.
PCH.obj has lost it's primary target of PCH.pch when the builder/executor is overwritten.
The target[0] change allows the PCH.obj node to be executed before the PCH.pch node is executed in some cases based on the lexical ordering of nodes.
This is seen in the build failures for PCH.obj as the command issued is to use the pch file rather than create the pch file.
[Optional] State C: env.PCH('PCH.cpp')
flowchart LR subgraph 3 ["State C: env.PCH('PCH.cpp') => msvc.pch_emitter"] direction LR N5[PCH.pch] --> B4["Builder $PCHCOMSTR"] --> E4["Executor $CXX ... <br> target=[PCH.pch, PCH.obj], source=[PCH.cpp]"] N6[PCH.obj] --> B4 endCalling the env PCH method a second time after the environment StaticLibrary call restores the builder/executor for PCH.obj.
The first target for the PCH.pch and PCH.obj nodes is PCH.pch (e.g., target[0]==PCH.pch).
Can the dual assignment of build/emitter to PCH.obj be prevented? The possible solution below appears to solve this problem.
Possible Solution
SCons.Tool.msvc.object_emitter:
Current code
Possible solution code (annotated):
When the object_emitter is called for target PCH.obj and source PCH.cpp, the target list and source list is invalidated (i.e., both are set to None) which suppresses the assignment of the static object builder/emitter to the PCH.obj node (i.e., the pch builder/emitter is not overwritten).
By maintaining the original pch builder/emitter assignment for PCH.obj, the DAG walk evaluation order is deterministic which is desirable.
The PCH.pch node is executed before the PCH.obj node is executed.
Manual test results for proposed code:
With the proposed code change:
All manual tests result in the PCH.pch node being evaluated first which produces the PCH.pch and PCH.obj files regardless of the PCH.pch name and any lexical ordering as the initial PCH.obj target list from the PCH builder/emitter is preserved.
The automated test scons/test/MSVC/PCH-source.py passes regardless of source file order.
The automated tests for MSVC/MSVC (79 tests) all pass or have no result.
mwichmann commentedon Nov 12, 2023
Sorry I haven't had a chance to really look at this in detail yet, but the analysis looks on point. I did put up a PR to the docs last week that suggested not including the "pch source file" as a source elsewhere, as SCons will track it correctly from there. I presume that's really not enough of a "solution"? The previously referenced issue #2505 did suggest limited confidence that the fix applied there was entirely correct, which has proven to be true, since this detail of dueling emitters was not recognized.
jcbrill commentedon Nov 21, 2023
No worries.
The proposed solution above was tweaked a little and is now available for testing in PR #4444.
In limited testing, it appears to "do the right thing".
The PR passes for the 16 combinations of the four pairs:
The PCH-source test was modified to have "foo.cpp" at the end of the list which used to fail.
It might not be the worst idea to mention than there can only be one pch node per environment in addition to the requirement that the pch source file must be c++.
mwichmann commentedon Nov 21, 2023
Now that that's in a published version, I'm happy to receive concrete suggestions for improvement (which I will undoubtedly tweak further).... https://scons.org/doc/production/HTML/scons-man.html#b-PCH
bdbaddog commentedon Nov 30, 2023
@jcbrill - sorry for the delay in reviewing this and the PR.
So your suggested solution is to fix this under the hood and just make it work?
What happens if env['PCH'] is set, but the user never calls env.PCH(...) ?
jcbrill commentedon Nov 30, 2023
No need to apologize. I'm sorry for going missing the last few days.
Yes.
That is a really good question.
Without the
env.PCH(...)call, the output pch file will not be generated and the build fails.In the current implementation, there are different reasons for the build failure based on whether or not the pch source file is removed from the source file list:
In the suggested solution, there is an scons error regardless of whether the pch source file is in the source file list or not:
One could argue that it is more desirable to fail with an scons error rather than a c compiler error.
The results of the four runs are shown below based on the following combinations: (master, branch) x (pch source file included, pch source file removed).
Test results:
master (scons-master)
pch source file included in source list: c compiler error
fatal error C1083: Cannot open precompiled header file: 'build\debug\lib\core\static\a-pch.pch': No such file or directorypch source file not in source list: scons error
scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency 'build\debug\lib\core\static\a-pch.pch' not found, needed by target 'build\debug\lib\core\static\b-hello.obj'branch (jbrill-msvc-pchnode)
pch source file included in source list: scons error
scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency 'build\debug\lib\core\static\a-pch.pch' not found, needed by target 'build\debug\lib\core\static\b-hello.obj'pch source file not included in source list: scons error
scons: *** [build\debug\lib\core\static\b-hello.obj] Explicit dependency 'build\debug\lib\core\static\a-pch.pch' not found, needed by target 'build\debug\lib\core\static\b-hello.obj'EDIT: ADDENDUM
In the current implementation, the names of the source files matter.
In the case above (
a-pch.pch,b-hello.cpp) there are different errors.For (
b-pch.cpp,a-hello.cpp), there is only the scons dependency error.In the suggested solution, the same error is produced regardless of source file naming.
mwichmann commentedon Nov 30, 2023
Well, in this case (rephrasing from the previous comment) - you haven't given SCons the information of how a PCH file fits into the plumbing, so it shouldn't be expected to work. If the implementation were different, it might theoretically work if the PCH file were already present in the source tree, SCons just wouldn't know how to regenerate it, but since Microsoft also requires the "PCH object file" (don't even know what to call that) to be part of the link, it can't work. I guess one could ask - should
env['PCH']even have any meaning ifenv.PCH()hasn't been called, and just get ignored? But we don't have to solve every detail...bdbaddog commentedon Nov 30, 2023
It might be dumb, but the no PCH() should work. the pch.cpp file would basically be a no-op right?
mwichmann commentedon Nov 30, 2023
I get more confused the more time passes. We do this in various tests, so we're setting both (as you'd expect).
Meanwhile, there's a routine
get_pch_nodethat basically fishes out the node forPCH, andmslinkuses that to deduce the object file name and add it to thedllEmitterandprogEmitter, so I think it's not a no-op.jcbrill commentedon Nov 30, 2023
This. msvc also calls get_pch_node in the object emitter.
Once the pch node has been defined, the compile commands will include the pch header in the command-line (e.g.,
/Yucore/CorePCH.hpp) which would fail if there was not an explicit dependency error.I'm not sure there is a reliable way to know if env.PCH() has been called and when it was called (before or after the env['PCH'] assignment).
mwichmann commentedon Nov 30, 2023
I wonder if the idea is to say not to set the
PCHconsvar manually, and instead have thePCHbuilder be the one that sets it.jcbrill commentedon Nov 30, 2023
It appears that calling env.PCH() and not defining env['PCH'] fails with a python error (at least in the suggested version).
However, there is a non-trivial chance that the test configuration is completely messed up.
I don't have time to investigate further tonight, but will tomorrow morning.
jcbrill commentedon Dec 1, 2023
The suggested solution was adjusted to set
env['PCH']=pchin the msvc pch_emitter when eitherenv['PCH']is undefined or evaluates to false.A set of 24 experiments were run using the
4.6.0ish main branch and the suggested solutionjbrill-msvc-pchnode. The results of the experiments are shown below.Comments:
env.PCH()without settingenv['PCH']results in python errors in the current implementation in some cases. The taskmaster eventually tries to call a node's executor method when the node's executor isNone.env['PCH']without callingenv.PCH()results in c errors and scons errors in the current implementation.env['PCH']without callingenv.PCH()results in scons errors in thecurrrentsuggested implementation.At present, I'm not sure that setting
env['PCH']without callingenv.PCH()can be turned into a no-op.Experiment Results
Column legend for tables:
env.PCH()):env.PCH()env.PCH()env.PCH()beforeenv['PCH']assignment, if any):env.PCH()not calledenv.PCH()is called afterenv['PCH']assignment, if anyenv.PCH()is called beforeenv['PCH']assignment, if anyenv['PCH']):env['PCH']env['PCH']NOTE: Pass does not mean that precompiled headers are being used, simple that the library build successfully.
Branch
4.6.0(total: 24, fail c: 3, fail python: 4, fail scons: 3, pass: 14):Branch
jbrill-msvc-pchnode(total: 24, fail c: 0, fail python: 0, fail scons: 4, pass: 20):Edits:
mwichmann commentedon Nov 20, 2026
My inclination now is to close this issue citing unsupported usage, and add some small doc notes to clarify things to do/not do. Meanwhile, if people think it's useful (I'll wait for @jcbrill and @bdbaddog at least), open a new issue to track the more specific problem that the now-abandoned #4444 was after (prevent overwriting the PCH node), so we don't lose track of that real issue, but it's more focused than "wait, what, it matters what the PCH source file is named???"
There are a lot of complex pieces that lead to the result we see, which is a true headscratcher - why would it matter what letter the filename starts with? At the very deepest level, the problem is that the thing we care about isn't in the dependency graph, so instead of picking the right dep from the graph, we go searching through a filesystem listing, and those are explicitly sorted to ensure repeatabilty. How we get there... much of it is in the material above so I won't attempt a rehash.