scope,make , Reuse a Make Variable

Reuse a Make Variable


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

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

BUILD_DIR := ./build/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:


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


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_DIR := ./build/a

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

BUILD_DIR := ./build/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.


How does MAKE remember the file timestamps

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...

AngularJS Set Value to $scope from Nested Function

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

Scope in javascript acting weird

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 {}...

Global variables, Jquery

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...

make error during building webkitgtk

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...

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

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...

Eclipse Makefile: Make Variables are skipped

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++:...

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

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...

AngularJS call function from click

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 exactly works the Javascript variable scope? [duplicate]

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;...

makefile read reused variable inside recipe

In trying to implement nonrecursive make, I have a 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))...

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

I created the following 3 files: base.js var base = {}; = 1; base.two = 2; base.three = 3; = 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 =...

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

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...

exists and sapply: why are these functions different?

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) {...

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

I cam across the following command in a makefile: %-nosyms.$(TARGET).elf: $(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?

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?...

Using a variable outside of it's 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 =...

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

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?

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...

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

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...

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

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...

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

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:...

'using' scope in C# and 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...

Returning a pointer which is a locally declared wchar_t

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...

Assign and use of a variable in the same 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...

Haskell make recipe fails for Paradox theorem prover using GHC

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...

Variable scoping in Swift with tasks

I've got all of this code inside of a function in my view controller: self.activityIndicator.startAnimating() let url = NSURL(string: "") 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:...

Nested For loop in makefile

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}"; \...

Java inheritance and Scope of variable

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)...

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

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

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

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...

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

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(...

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

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...

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

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...

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

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 }...

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

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:...

calling the parent controller function in Ext.Ajax.request

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...

basic makefile ifeq how to

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...

Multiple Scope value in Binding (Specflow)

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...

Reload controllers after scope change (AngularJS)

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)...

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

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...

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

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...

Why is fileinput.input object not lost when going out-of-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):...

Makefile overriding default implicit rule

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 % :...

A make rule for verbosity

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...

xcode 6.3.2 external build

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...

C programming - Confusion regarding curly braces

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)...

JavaScript function parameter and 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...

Dot in front of variables in make files

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!...

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

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']);...