scope,make , Reuse a Make Variable


Reuse a Make Variable

Question:

Tag: scope,make

I'm compiling a lot of very similar object files using make and want to do something similar to the following:

BUILD_DIR := ./build/a
BUILD_DIRS += $(BUILD_DIR)

a:
    $(CC) $(BUILD_DIR)/file.c

BUILD_DIR := ./build/b
BUILD_DIRS += $(BUILD_DIR)

b:
    $(CC) $(BUILD_DIR)/file.c

Problem is that when I run

make a

The value of BUILD_DIR is build/b. I expected it would be build/a, when does make resolve the variable names? Is there any easy to read way to do what I want? I tried define/endef but got the same results.

Edit: Note that the suggested answer Immediate variable expansion in recipe won't really solve this problem. The answer there is to use target-specific variables. Note that I also need to use the variable with a non-target-specific variable:

BUILD_DIRS += $(BUILD_DIR)

If the variable is target-specific I won't be able to use it outside of the target like I want.


Answer:

Etan's answer regarding target-specific variables will solve your problem, you just need to realize that := (immediate / simple) target-specific variables are resolved at assignment time, just like other := variables.

So, this will work:

# Force this to be a simple variable
BUILD_DIRS :=

BUILD_DIR := ./build/a
BUILD_DIRS += $(BUILD_DIR)

a: BUILD_DIR := $(BUILD_DIR)
a:
        $(CC) $(BUILD_DIR)/file.c

BUILD_DIR := ./build/b
BUILD_DIRS += $(BUILD_DIR)

b: BUILD_DIR := $(BUILD_DIR)
b:
        $(CC) $(BUILD_DIR)/file.c

Personally I suspect there are better ways to do this but without more information about the requirements you really need to meet it's not useful to speculate.


Related:


Multiple requires of same module seem to affect scope of each successive require


node.js,module,scope
I created the following 3 files: base.js var base = {}; base.one = 1; base.two = 2; base.three = 3; base.bar = function(){ console.log( this.three ); }; a.js var base = require('./base'); base.three = 6; module.exports = base; b.js var base = require('./base'); module.exports = base; test.js var test_modules =...

make: *** No rule to make target 'rm', needed by 'clean.Stop


c++,makefile,make
I am working with cygwin on windows 8.1. I have used the following make file .SUFFIXES : .o .C CFLAGS = -g2 CC =g++ ${CFLAGS} LIBRARIES = -lm .C.o : ${CC} -c $< SOURCE-FILES = sparsegraph.C myvarious.C pairlist.C graphlist.C peo.graph.C choldc.C copy.C metropolis_fns.C likelihood.C metropolis.C OBJECT-FILES = sparsegraph.o myvarious.o pairlist.o...

How to correctly make install of binaries and data after compile in linux?


linux,make,install
After make of sources I have compiled executable file and data directory with images for it. What should I do at "make install" phase to correctly install these files to the linux system? And how then application can find installed data (in case when binary and data are placed in...

exists and sapply: why are these functions different?


r,scope,sapply
Why are the two functions fn and gn below different? I don't think they should be, but I must be missing something. vars <- letters[1:10] a <- b <- 1 fn <- function (d) { sapply( vars, exists ) } gn <- function (d) { sapply( vars, function (x) {...

basic makefile ifeq how to


makefile,make,gnu-make
I am just learning about Makefiles and am having trouble with ifeq. Version = GNU Make 3.82 Here is my simple Makefile: CHECK := 0 CHECK2 := 0 check : @echo "Check=${CHECK}" @echo "Check2=${CHECK2}" ifeq (${CHECK2},${CHECK}) @echo "EQUAL" else @echo "NOT EQUAL" endif Here is the output: Check=0 Check2=0 NOT...

Using a variable outside of it's scope


swift,scope
I wish to access a variable outside of it's scope. (A snippet of the relevant code is posted). Within the @IBAction ,the sphereNode.runAction(moveUp) is not recognised. I cannot simply declare sphereNode global as it is dependant upon the sphereGeometry declaration. override func viewDidLoad() { super.viewDidLoad() //Added our first shape =...

What does the following makefile command do? /no-symbols-control-file


makefile,make,gnu-make,binaryfiles,contiki
I cam across the following command in a makefile: %-nosyms.$(TARGET).elf: %.co $(PROJECT_OBJECTFILES) $(INTERRUPT_OBJECTFILES) contiki-$(TARGET).a $(CC) $(CFLAGS) -o [email protected] $(filter-out %.a,$^) $(filter %.a,$^) $(filter %.a,$^) $(LDFLAGS) Source: Contiki/cpu/arm/stm32f103/Makefile.stm32f103 . Does this command generate no-symbols-control-file? What is the use of a no symbol image file?...

what does -wl, --start-group mean in make file?


make
I have this in my Make file.. # Create list of object files # LIB_OBJS = -Wl,--start-group \ $(T_OBJ_DIR)/Source1.o \ $(T_OBJ_DIR)/Source2.o \ $(T_OBJ_DIR)/Source3.o \ $(T_OBJ_DIR)/Source4.o \ $(T_OBJ_DIR)/Source5.o \ -Wl,--end-group \ Could anyone please explain What "-Wl,--start-group" and "-Wl,--end-group" mean?...

Access declared variables via `this` in non-global scopes


javascript,scope
var x = 16; console.log(this["x"]); // 16 I'm ok with this, but: (function () { var y = 16; console.log(this["y"]); // undefined }()); Why we cant access variables via this ?! I know it's possibe when we assign values, for example: (function () { x = 16; // will assigned...

Returning a pointer which is a locally declared wchar_t


c,static,scope,return
I've read a lot of questions about returning pointers in C, but am still confused with the issue of scope. The following code works because of the call to malloc, and one possible output might end up being Wide string: StackOverflow. #include <stdlib.h> #include <string.h> #include <stdio.h> #include <wchar.h> static...

Reload controllers after scope change (AngularJS)


javascript,angularjs,view,routes,scope
so I have this controller for swapping languages app.controller("langCtrl",['$scope','$route',function($scope,$route){ this.swap_lang = function(){ if(lang == "tr"){ lang = "en"; }else{ lang = "tr"; } console.log(lang); this.lang = lang; //$route.reload(); //$scope.$apply(); }; }]); And this one below is supposed to be responsible for bringing up menus (JSON files with short language codes)...

Assign and use of a variable in the same subshell


bash,scope,subshell
I was doing something very simple like: v=5 echo "$v" and expected it to print 5. However, it does not. The value that was just set is not available for the next command. I recently learnt that "In most shells, each command of a pipeline is executed in a separate...

JavaScript function parameter and scope


javascript,function,scope
I have done some tests with codes listed below: function foo(x) { alert(y); } var y = 'I am defined outside foo definition'; foo(); The above code gives me an alert 'I am defined outside foo definition'. Then another test: function bar(x) { alert(x); } var x = 'I am...

What is the scope of public variable in different methods of a same class in Console C#


c#,variables,scope
I have a class named Data that is used to retrieve a user's data class Data { public string firstName; public string lastName; public void getdata() { firstName = "ABC"; lastName = "XYZ"; } public static XDocument GetDataToXml() { var objget = new Data(); objget.getdata(); XDocument doc = new XDocument(...

Makefile overriding default implicit rule


c++,c,makefile,make
Why this rule cannot override the default implicit rule ? When make is invoked like: make myapp (suppose myapp.c is there). The make runs the default command to build and link the program instead the commands defined in this implicit rule: #... omitted code LCUS=$(LIBS)/libcus.a #... omitted code % :...

Why is my custom php.ini file not loaded site wide while placed in /public_hml? [duplicate]


php,configuration,scope,ini,public-html
This question already has an answer here: Custom php.ini per-directory (for testing sites) 2 answers I created a custom php.ini ... it's located in /public_html. Shouldn't it be valid and used for the whole site and directories under public_html ? It seems not to be loaded e.g. in /public_html/cms/usr...

Eclipse Makefile: Make Variables are skipped


eclipse,makefile,make
I have a project with a Makefile in it, on Unix console it works fine, compiles, builds and I can run the binary at the end. I imported the project into Eclipse workspace and somehow Makefile module of Eclipse cannot build the project now. It gives the following error: g++:...

AngularJS call function from click


javascript,html,angularjs,scope
I can't for the life of me figure out why I can't call this function in my controller. On clicking an accordion-group attribute I get this error: Uncaught ReferenceError: getConversationsForUser is not defined Here is the html: <ui-view id="smtConvoCard" layout="column" layout-fill layout-padding> <div layout="row" flex layout-align="center center"> <md-card flex-gt-sm="90" onresize="resize()"...

How to change value of variable from a different .py file in Python


python,scope
From a file foo.py, I want to change the value of a variable which's placed in a different file, let's say bar.py. I've tried to do it importing the variable, but it seems that it's imported not as reference. Just examples: bar.py: age = 18 foo.py: from bar import age...

Javascript - Calling A Variable From Outside Of If/Else Block Returns Undefined


javascript,node.js,scope,global-variables
I thought this is how you make a variable inside a if/else block global (Case 3). connection.query(sql, function (err,rows){ //Handle Errors if(err){ //Log The Error & Die } //If Successful - Log Results For Now (Change To Export Results) else { //console.log(rows); foo = rows; } }); console.log(foo); // Out:...

AngularJS Set Value to $scope from Nested Function


javascript,angularjs,scope,angularjs-scope,closures
I'm trying to get a value from a function inside a function: Controller $scope.vm = {}; function myFunc(){ $scope.vm.hello = 'Hello'; function myFunction(){ $scope.vm.world = 'world'; } } myFunc(); View <p>{{vm.hello}} {{vm.world}}</p> Here's my Plunk. How can I get this to display "Hello world"?...

How does MAKE remember the file timestamps


c,make
I've found this question which is basically asking the same, but got no real answer. Where is the make's config file / database file where it remembers the file timestamps, so it can tell what changed? I checked and there's no .make or similar in my project, nor in the...

Java inheritance and Scope of variable


java,inheritance,scope
The Program is: class A { int i = 10; } class B extends A { int j = 20; } class C extends B { int k = 30; } class D extends C { int m = 40; } public class asg2 { public static void main(String[] args)...

What's the difference between [email protected] and $1 when there is only one parameter?


makefile,make
There are some C code: apple.c #include<stdio.h> int main(void) { printf("apple\n"); return 0; } Makefile apple: gcc -c [email protected] gcc [email protected] -o [email protected] $ make apple and it works perfectly. But if I modify Makefile as: apple: gcc -c $1.c gcc $1.o -o $1 $ make apple It does not...

Scope in javascript acting weird


javascript,function,scope,pass-by-reference
Object are passed with their reference in javascript. Meaning change in that object from any where should be reflected. In this case, the expected output was {} for console.log(a) function change(a,b) { a.x = 'added'; a = b;//assigning a as {} to b } a={} b={} change(a,b); console.log(a); //expected {}...

Nested For loop in makefile


shell,makefile,make
I am trying to loop through the .c files in a specific directory through the makefile. i used the following code, but it seems not working: DIR= Sources \ Sources_2 @for entry in ${DIR} ; \ do \ @for i in $${entry}/*.c ; \ do \ echo "Processing $${i}"; \...

Problems with Flash 8 (AS2), Timelines, and Variable Scopes


flash,variables,scope,actionscript-2
Okay, so trying to not post 5 pages of information, I'll start with the following: In a movie clip, I have 3 keyframes. I'm trying to edit a textbox on each frame, but I've found previously that only the text box in the current frame is accessible. In an attempt...

Is there a lazy functional (immutable) language where functions have intermediate variables+return?


scope,functional-programming,lazy-evaluation
I apologize if this has an obvious answer. I would like to find a lazy functional programming language where the following pseudo code makes sense: let f = function(x) { let y = x*x // The variables y and z let z = y*2 // are local return z }...

make error during building webkitgtk


linux,makefile,cmake,make
I use UBuntu 14.04 LTS. I need to build webkitgtk 2.8.3 Here is an example instruction which I have used: linuxfromscratch When I run sudo make -j8 I get following log: Scanning dependencies of target JavaScriptCore-4-gir Scanning dependencies of target fake-generated-webkitdom-headers [ 0%] Scanning dependencies of target WebKit2-fake-api-headers Scanning dependencies...

Why is fileinput.input object not lost when going out-of-scope?


python,scope
In the following code I would expect than python is freeing fileinput.input when I'm returning in the middle my loop as it is going out-of-scope. However, when calling again my function fileinput tells me raise RuntimeError, "input() already active" Here is my code: def func(inplace): for line in fileinput.input(sys.argv[1], inplace=inplace):...

Javascript variable is set in one function, but undefined in another function


javascript,jquery,namespaces,scope
I have the following Javascript, eventManager: { $musicGenres : null, // $musicGenres is the selector for a div-container of inputs musicGenres : [], // Functions handle : function(selectors) { selectors = (typeof selectors === 'undefined') ? { 'musicGenres' : '#musicGenres' } : selectors; // selectors default values... this.$musicGenres = $(selectors['musicGenres']);...

Dot in front of variables in make files


makefile,make,gnu-make
I am not able to figure out what does a dot . in front of a variable in makefile does. For e.g.: SOURCEDIRS = . $(PROJECTDIRS) $(TARGET_DIRS_CONCAT) vpath %.c $(SOURCEDIRS) It would be great if someone could tell me. Thanks!...

Multiple Scope value in Binding (Specflow)


scope,automated-tests,specflow,feature-selection,feature-file
I have a method which runs Before a feature like so, [BeforeFeature, Scope(Feature = "Feature1"] Method() { } I want the same method to be ran for another feature file that i've wiritten i.e. Feature2 How do i combine this "Feature2" in the scope Binding? I tried this [BeforeFeature, Scope(Feature...

C programming - Confusion regarding curly braces


c,scope
The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces. This one is actually running fine: #include <stdio.h> #include <stdlib.h> int main() { int ch, lastch; lastch = 'a'; while((ch = getchar())!= EOF)...

Python: Unable to import global variable initialized in setUp method from init file


python,scope,global-variables,python-unittest
I have a package with testing modules and inside the init file I have a setUp method with some operations. These operations are executed correctly before any unit test in the package's modules run. Inside the setUp method I'd like to initialize a global variable and then access it from...

xcode 6.3.2 external build


c++,xcode,makefile,make
I'm trying to compile an existing c++ project, originally developed on linux with gcc. The only external library is GSL (GNU Scientific Library). I have created an external build tool project to use xcode's debugger, but I currently have two issues. 1) When I try to build in xcode it...

Why does gcc search header files from non-exist folders?


c,linux,gcc,compiler-errors,make
I am trying to build an open source project shark on CentOS 7, and get very weird build errors: make: *** No rule to make target `/usr/lib/gcc/x86_64-linux-gnu/4.8/include/stdarg.h', needed by `core/luv/luv.o'. make: *** No rule to make target `/usr/lib/gcc/x86_64-linux-gnu/4.8/include/stddef.h', needed by `core/luv/luv.o'. make: *** No rule to make target `/usr/lib/gcc/x86_64-linux-gnu/4.8/include-fixed/limits.h', needed...

Global variables, Jquery


javascript,jquery,variables,scope
I have the following code oss = $("#us"); mainLogo = $("#mainLogo"); container = $(".container"); $(document).ready(function(){ oss.hide(); oss.fadeIn(1000); mainLogo.hide(); mainLogo.fadeIn(1000); container.find("#images").hide(); container.find("#images").slideDown(); }) $(oss).click(function(){ container.fadeOut(); }) The problem I have is that I can't seem to access the variables outside. I've tried window.varName, just writing var infront etc. But the compiler...

calling the parent controller function in Ext.Ajax.request


extjs,view,controller,scope
I have a login Page which authenticates the user.On correct username and password it should hide the loginview and display the next view.When I call the function to do the same it gives an error saying "Uncaught TypeError: this.functionname is not a function.Here is my code for the same: startMain...

Variable scoping in Swift with tasks


ios,swift,scope
I've got all of this code inside of a function in my view controller: self.activityIndicator.startAnimating() let url = NSURL(string: "http://www.google.com") var request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "PUT" var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(["notes": self.textView.text], options: nil, error: &err) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var s = NSString(data:...

How exactly works the Javascript variable scope? [duplicate]


javascript,variables,scope
This question already has an answer here: What is the scope of variables in JavaScript? 13 answers I am pretty new in JavaScript and I have some doubts related to the variable scope. So I tryed to do this example: function outer() { alert("INTO outer()"); var val1 = 1;...

accessing a variable from outside a function and returning the variable. In a module pattern


javascript,function,module,scope
I'm learning about how to split up different functionalities into different section so I could have loose coupling. i have two object 1.'addition' and 2. 'subtraction'. I don't think that info matters for this Q. what i want to do is that when amount = 3 in the index.html file...

in ActiveRecord::Relation, is it preferable to scope by parent in the model or set @parent in the controller


ruby-on-rails-4,activerecord,model-view-controller,scope,parent-child
I have a class which belongs to another. course.rb class Course < ActiveRecord::Base belongs_to :school I currently use a before_action to set the parent instance in the controller. courses_controller.rb class CoursesController < ApplicationController #returns @school. only: [methods] avoids trying to set @school when no school param expected before_action :set_school, only:...

A make rule for verbosity


makefile,make
Typically we have this in a Makefile %.o:%.c $(cc) $(flags) -o [email protected] -c $< When the amount of flags is huge, I feel better to write this instead %.o:%.c $(info $(cc): $< --> [email protected]) @$(cc) $(flags) -o [email protected] -c $< However it can be useful to sometime see everything. So...

Haskell make recipe fails for Paradox theorem prover using GHC


linux,haskell,make,ghc,theorem-proving
I am trying to install the paradox theorem prover sourced from here. When I run the makefile this is the command that runs: ghc -optl -static -lstdc++ -I../instantiate -I../minisat/current-base ../minisat/current-base/Solver.or ../minisat/current-base/Prop.or ../instantiate/MiniSatWrapper.or ../instantiate/MiniSatInstantiateClause.or -fglasgow-exts -O2 -static -threaded -main-is Paradox.Main.main --make Paradox.Main -o paradox And it results in several errors like...

Can Make be made to understand that a/../z and b/../z are the same location?


makefile,make,gnu-make
I have a somewhat large and complex Makefile setup that postprocesses some data files. Overall it work quite well, but I have run into an annoying issue where Make builds the same target many times over under different directory names. As a simple example, consider the Makefile foo : 1/foo...

'using' scope in C# and sharpdx


c#,scope,using,sharpdx
The question is more C# related, but I started learining sharpdx recently and I came up on two ways to initialize resources. First stores the resource (Texture2D in this example) as a global variable. Then in code assigns the value to it and passes it to sharpdx's method (and down...

How to build a './configure && make && make install' software against a custom library which I also build?


linux,make,gnu,ld,configure
I am building tmux-2.0 from sources on a pretty regular Linux host. First attempt failed as it turned out that the version of libevent installed is older than required, so I proceeded to download and build libevent-2.0.22 from sources (current at the time of writing) first. Building of libevent succeeded...

What does $(@:.h=.h.d) mean in GNU make?


make
I'm maintaining a (horrendously complicated) Makefile, and in some recipes I saw the following: $(@:.h=.h.d) I have absolutely no clue as to how to interpret this, or whether there's any documentation on those characters. Obviously, Google won't work because it thinks I'm typing gibberish. I saw a related question about...

makefile read reused variable inside recipe


makefile,make
In trying to implement nonrecursive make, I have a Rules.mk which looks like: ############ # Enter Stack ############ sp := $(sp).x dirstack_$(sp) := $(d) d := $(dir) .. setup things like OBJECTS_$(d), DEPS_$(d), TARGET_$(d), etc ... ############ # Exit Stack ############ -include $(DEPS_$(d)) d := $(dirstack_$(sp)) sp := $(basename $(sp))...